Tuesday, October 16, 2012

Java Tidbits ............................(Initializers!)

A class has  instance vars and instance methods , constructors  and  init block and static init block.
The order of initializer block to be called is 
  1. declaration of  vars ( both static as well as non -static)
  2. static block
  3. init block
  4. constructor

declaration-before-reading Rule
declaration of a field must occur before its usage in any initializer
expression if the field is used on the RHS of an assignment in the initializer expression.
declaration-before-reading rule: it does not apply if the
initializer expression defines an anonymous class, as the usage then occurs in a different class which has its own accessibility rules in the enclosing context.
final static fields can only be initialized either at time of declaration or with in static block.


Here is an example 


public class MyInitializer {
   
     boolean flag = true;
     final static int ROOM=7;
     int l=h=8; // declaration-before-reading
     int f=  new mysmall(){
                 int getsmall( ){return h;}
                 }.getsmall();
     //mytest.BOOK;
     int k = getK(); 
   
     int  getK(){
        return h; // declaration-before-reading
     }

   
     static{
         NUM=200; // declaration-before-reading
        // ROOM=45;
         System.out.println("static init block "+ROOM);
     }
     {
         System.out.println(" instance init block ");

         try{
         if(flag )
             throw new Exception();
         }catch(Exception e){System.out.println(" caught in init block"+ROOM);}
     }
     int h=9;
   
     MyInitializer(){
           
         System.out.println(" A constructor will be called in end "+ROOM);
     }
     private static int NUM;
   
     interface mytest { int BOOK=60;}
     class mysmall{ int getsmall( ){return 20;} }

    public static void main(String args[]){
        MyInitializer mObj = new MyInitializer();
        System.out.println(" mObj.f="+ mObj.f + " mObj. k="+mObj.k + " NUM"+NUM);
        // both k & f will be 0 since h is not initialized .
        // if h is initialized  before then it will take its value
        // here its picking 8  since h 's value is overwritten
    }
}

No comments: