Tuesday, August 24, 2021

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 classes are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular questions is the difference between inner class and nested static class , some time also referred to as a difference between static and non static nested class in Java. One of the most important questions related to nested classes are Where should you use nested class in Java?


This is one of the tricky Java questions, 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 the 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 a nested static class in Java?

A nested static class is another class that is declared inside a class as member and made static. A nested static class is also declared as a 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 a 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 an instance of the 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 a very trivial example of a nested static class, it demonstrates some properties of a nested static class. A better example of a nested static class can be implementing a custom Comparator e.g. OrderByAmount in How to sort ArrayList of 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 the static keyword in their class declaration, which means they are static members of the class and can be accessed like any other static member of the 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.

Nested static, Inner and Anonymous class in Java


That's all on What is Inner class and nested static class in Java. We have seen local, anonymous and member inner classes and differences 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.



9 comments:

  1. Mid-skilled Java programerDecember 29, 2012 at 7:18 PM

    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".

    ReplyDelete
  2. 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

    ReplyDelete
  3. @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

    ReplyDelete
  4. Hi,

    Nice article.

    Can you please provide information about

    - what and how the nested classes can access members of the enclosing class.

    ReplyDelete
  5. @Nithya : we don't need to create obj via outer class,we can even do,
    inner cl = new inner();
    cl.go

    ReplyDelete
  6. Why can't inner class(non-static nested class)contain static fields and methods ? And what is the reason behind static nested class containing both static and non-static fields and methods? -@Atul

    ReplyDelete
  7. Inner classes and annonmouse classes are by default Thread safe or not

    ReplyDelete
  8. The output of first program is (Inner class Example in Java) is :
    Example of Local class in Java
    Anonymous class example in java
    Inner class example in java

    and not :
    Example of Local class in Java
    Inner class example in java
    Anonymous class example in java

    ReplyDelete
  9. Just a small addition in the difference.
    1) Inner class cannot have static members , because the inner class is reliant on the instance of enclosing class.

    2) Nested static classes can obviously have static members.

    ReplyDelete