What is the difference between static classes and non-static inner classes in Java?

Java 8Object Oriented ProgrammingProgramming

Following are the notable differences between inner classes and static inner classes.

Accessing the members of the outer class

The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class.

Example

public class Outer {
   int num = 234;
   static int data = 300;
   public static class Inner{
      public static void main(String args[]){
         Outer obj = new Outer();
         System.out.println(obj.num);
         System.out.println(data);
      }
   }
}

Output

234
300

The non inner class can access the members of its outer class (both instance and static) directly without instantiation.

Example

Live Demo

public class Outer2 {
   int num = 234;
   static int data =300;
   public class Inner{
      public void main(){
         System.out.println(num);
         System.out.println(data);
      }
   }
   public static void main(String args[]){
      new Outer2().new Inner().main();
   }
}

Output

234
300

Having static members in inner class

You cannot have members of a non-static inner class static. Static methods are allowed only in top-level classes and static inner classes.

raja
Published on 08-Jan-2018 11:47:24
Advertisements