Suggested Pages

Friday, May 25, 2012

Java Nested Classes: Inner Class, Static Class, Local Class

nested non-static classes (Inner Classes)

 public class OuterClass {
 
   private int id;
 
   private static String name="nome";

   class InnerBean {
  
     private int a;
  
     public void doThis(){
        System.out.println(OuterClass.name);
        System.out.println(OuterClass.this.id);
     }
  
   }

 }
The creation of an Inner class instance depends on the creation of the Outer class instance. Suppose you have just created an instance of the Outer class:
 OuterClass outerclass=new OuterClass();

To create the inner class you have to write the following code:
 InnerBean innerBean =outerclass.new InnerBean(); 

  • An Inner class can access static and instance variables of the Outer Class;
  • An Inner class can't declare static variable.


nested static classes


 public class OuterClass {
 
    private int id;
 
    private static String name="nome";

        static class InnerStatic {
  
            private int a;
  
            private static int b;
  
            public void doThis(){
              System.out.println(OuterClass.name);
           }
        }
 }
To create the nested static class you have to write the following code.
  Bean.InnerStatic innerStatic=new Bean.InnerStatic();
  • A nested static class is like a top-level class;
  • A nested static class can't access instance variables of the outer class.


Local Classes


public class OuterClass {
 
 private int id;
 
 private static String name="nome";

    public void doThis(){
        
        final String innername="hi!";
         
        class LocalInner{
      
            public void doThat(){
              System.out.println(innername);
            }
         }
    }
}

  • A Local Class is an InnerClass declared inside a block of code;
  • A Local Class can only access final variable declared in the same block code.

No comments :

Post a Comment

Suggested Pages