InitBlockDemo.java

 

Download InitBlockDemo.java source file

/* Demo of initialization blocks in Java.
 *
 * Written 8/2005 by Wayne Pollock, Tampa Florida USA
 *
 * Steps to initialize ``f'' from the code: Foo f= new Foo();
 *
 *  1.  Classloader locates Foo.class file, and any dependent classes
 *      (e.g.,superclasses).
 *  2.  Byte code is verified.
 *  3.  Sufficient RAM is allocated for all Class object fields.
 *  4.  All static properties are initialized to default (zero, false, null)
 *      values.
 *  5.  Static fields and static initialization blocks are executed in the order
 *      they appear.
 *  6.  Sufficient RAM is allocated for  all instance fields, included inherited
 *      ones.
 *  7.  All instance properties are initialized to default (zero, false, null)
 *      values.
 *  8.  Instance variables and initialization blocks are executed in the order
 *      they appear.
 *  9.  If the first line of the matched constructor calls a second constructor
 *      (via this), that constructor is invoked.  (Constructor chaining.)
 * 10.  If a constructor is invoked (directly or via chaining) that doesn't start
 *      with a call to this, a superclass' constructor is invoked.  You can pick
 *      one using super, or if the constructor doesn't start with a super call,
 *      the superclass' no-arg constructor will be used.
 * 11.  The body of the matched constructor is executed.
 *
 * Steps 1-5 occur only once in the lifetime of the JVM.  The rest occur each
 * time a new object is created.
 */

class InitBlockDemo
{
   private static int nextID;
   public int idNum;
   public String name;

   static {
      nextID = 1;  // complex DB lookup goes here
      // Add shutdown hook here
   }

   {
      idNum = nextID++;   // Run before any constructor
   }

   InitBlockDemo ()
   {
      this( "unknown" );  // Constructor chaining
   }

   InitBlockDemo ( String name )
   {                      // Object's no-arg constructor is invoked here.
      this.name = name;
   }

   public static void main ( String [] args )
   {
      InitBlockDemo ibd1 = new InitBlockDemo( "Hymie" );
      InitBlockDemo ibd2 = new InitBlockDemo();
      System.out.println( "ibd2.idNum = " + ibd2.idNum );
   }
}