Wednesday, December 26, 2012

Inner class and nested Static Class in Java with Example

Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular question is difference between inner class and nested static class , some time also refereed as difference between static and non static nested class in Java. One of the most important question related to nested classes are Where should you use nested class in Java? This is one of the tricky Java question, If you have read Effective Java from Joshua Bloch than in one chapter he has suggested that if a class can only be useful to one particular class, it make sense to keep that inside the class itself  otherwise declare it as top level class. Nested class improves Encapsulation and help in maintenance. I actually look JDK itself for examples and if you look HashMap class, you will find that Map.Entry is a good example of nested class in Java. Another popular use of nested classes are implementing Comparator in Java e.g. AgeCompartor for Person class. Since some time Comparator is also tied with a particular class, it make sense to declare them as nested static class in Java.  In this Java tutorial we will see what is Inner class in Java, different types of Inner classes, what is static nested class and finally difference between static nested class and inner class in Java.

What is Inner Class in Java

Any class which is not a top level or declared inside another class is known as nested class and out of those nested classes, class which are declared non static are known as Inner class in Java. there are three kinds of Inner class in Java:
  1. Local inner class
  2. Anonymous inner class
  3. Member inner class
Local inner class is declared inside a code block or method. Anonymous inner class is a class which doesn't have name to reference and initialized at same place where it gets created. Member inner class is declared as non static member of outer class. Now with Inner class first question comes in mind is when to use Inner class in Java, simple answer is any class which is only be used by its outer class, should be a good candidate of making inner. One of the common example of Inner classes are Anonymous class which is used to implement Thread or EventListeners like ActionListerner in Swing, where they only implement key methods like run() method of Thread class or actionPerformed(ActionEvent ae).

Here are some important properties of Inner classes in Java:

1) In order to create instance of Inner class, an instance of outer class is required. Every instance of inner class is bounded to one instance of Outer class.

2) Member inner class can be make private, protected or public. its just like any other member of class.

3) Local inner class can not be private, protected or public because they exist only inside of local block or method. You can only use final modifier with local inner class.

4) Anonymous Inner class are common to implement Runnable or CommandListener where you just need to implement one method. They are created and initialized at same line.

5) You can access current instance of Outer class, inside inner class as Outer.this variable.

Inner class Example in Java

Here is an example of member inner class, local inner class and anonymous inner class. For simplicity we have combined all examples of different inner class in one.

public class InnerClassTest {

    public static void main(String args[]) {
     
        //creating local inner class inside method
        class Local {
            public void name() {
                System.out.println("Example of Local class in Java");
             
            }
        }
     
        //creating instance of local inner class
        Local local = new Local();
        local.name(); //calling method from local inner class
     
        //Creating anonymous inner class in java for implementing thread
        Thread anonymous = new Thread(){
            @Override
            public void run(){
                System.out.println("Anonymous class example in java");
            }
        };
        anonymous.start();
     
        //example of creating instance of inner class
        InnerClassTest test = new InnerClassTest();
        InnerClassTest.Inner inner = test.new Inner();
        inner.name(); //calling method of inner class

    }
 
    /*
     * Creating Inner class in Java
     */

    private class Inner{
        public void name(){
            System.out.println("Inner class example in java");
        }
    }
}
Output:
Example of Local class in Java
Inner class example in java
Anonymous class example in java

What is nested static class in Java

Nested static class is another class which is declared inside a class as member and made static. Nested static class is also declared as member of outer class and can be make private, public or protected like any other member. One of the main benefit of nested static class over inner class is that instance of nested static class is not attached to any enclosing instance of Outer class. You also don't need any instance of Outer class to create instance of nested static class in Java. This makes nested static class very convenient to use and access.

Nested Static Class Example in Java
Here is an example of nested static class in Java. It look exactly similar to member inner classes but has quite a few significant difference with them, e.g. you can access them inside main method because they are static. In order to create instance of nested static class, you don’t need instance of enclosing class. You can refer them with class name and you can also import them using static import feature of Java 5.

public class NestedStaticExample {

    public static void main(String args[]){
 
        StaticNested nested = new StaticNested();
        nested.name();
    }
 
    //static nested class in java
    private static class StaticNested{
        public void name(){
            System.out.println("static nested class example in java");
        }
    }
}

Though this is very trivial example of nested static class, it demonstrate some properties of nested static class. Better example of nested static class can be implementing a custom Comparator e.g. OrderByAmount in How to sort Object in Java using Comparator.

Difference between Inner class and nested static class in Java.

Both static and non static nested class or Inner needs to declare inside enclosing class in Java and that’s why they are collectively known as nested classes  but they have couple of differences as shown below:

1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.

2) Another difference between Inner class and nested static class is that later uses static keyword in there class declaration, which means they are static member of class and can be accessed like any other static member of class.

3) Nested static class can be imported using static import in Java.

4) One last difference between Inner class and nested static class is that later is more convenient and should be preferred over Inner class while declaring member classes.


That's all on What is Inner class and nested static class in Java. We have seen local, anonymous and member inner classes and difference between Inner class and nested static class in Java. Worth noting is where to use nested static class or Inner class ? Joshua Bloch has suggested to prefer nested static class over Inner classes in his book Effective Java. Some time Interviewer ask you to write code to create instance of inner class which can be tricky if you haven't used them recently. Just remember that every inner class instance is associated with one outer class instance.

3 comments :

Mid-skilled Java programer said...

Nice article. The one question I never seem to find a good ansewr to is "why using nested static classes", and you answered it nicely and simply in the section "What is nested static class in Java".

Nithya S said...

public class Static_class {

static class inner()
{
void go()
{
System.out.println("Hello");
}
}
public static void main(String s[])
{
Static_class.inner cl=new Static_class.inner();
cl.go();
}
}

in this class i create obj for static inner class . but static class act as class level variable . then why we created obj ? please explain me

Anonymous said...

@Nithya : we need to create obj since go method is not static .To access non static methods we need to create obj .If go method become static then no need to create obj access them by class name

Post a Comment