Saturday 2 April 2016

Static member class vs. nonstatic

Wherever you use a static member class, you can always remove the static keyword, and it still works. But it will have an unnecessary reference to the enclosing instance (the Outer class's instance)

If we add static on Inner class, it won't compile. Because static member class doesn't know about Outer class's instance.

 public class Outer {  
   public void doit(){  
     Inner inner = new Inner();  
     inner.doit();  
   }  
   private void doitAgain(){  
     System.out.println("do it again");  
   }  
   private class Inner {  
     public void doit() {  
       Outer.this.doitAgain();  
     }  
   }  
   public static void main(String[] args){  
     new Outer().doit();  
   }  
 }