Wednesday, July 15, 2015

Inner Classes-2(Local Classes)

         In java you could define a class inside a code block/Method. This kind of classes are known as Local classes .       Lets look at an Example :
   
public class HelloWorld{
    public int studentId;
 
 public  void method(){
    int loop=0;
    final int CONSTANT=10;
    System.out.println("Main Execution begins , Student id is :" +studentId);
    class  LocalClass{
     public void printStudentId(){
      System.out.println("Inside Inner class, Student id is :" +studentId); // Remember that if studentId is also present in local class
                                                                         // this will print the local class variable student id , in such cases  use Student.this.studentId
                                                                         
            System.out.println("Inside Inner class, CONSTANT is :" +CONSTANT); // only final local variables can be accessed.
            
             System.out.println("Inside Inner class, loop is :" +loop); // errors out , loop is not final
   }
   }
   LocalClass local = new LocalClass();
   local.printStudentId();
   }
   
   
   public static void main(String args[]){
       HelloWorld hello = new HelloWorld();
       hello.method();
   }
   
   }

Some points to remember:
 1. A local class can access variables inside outer class (instance variables of outer class)
 2. A local class cannot be instatiated/visible outside the code block/method.
 3. A local class cannot access non final local variables as they both have different scopes , Local variables get destroyed on method exit . But final local variables are accessible inside local classes. Final variables are copied to the code stack internally before the inner class instance is created and can be used inside.

No comments:

Post a Comment