Suggested Pages

Monday, May 21, 2012

Static block, Instance block and Constructor

Given the following class A which is the output of A a=new C(); ?

A.java
package a;
public class A {
 static {
      System.out.println(“1”);
 }
 {
      System.out.println(“2”);
 }
 A(){
      System.out.println(“3”);
  }
}

class B  extends A {
  static {
      System.out.println(“4”);
  }
  {
      System.out.println(“5”);
  }
  B(){
      System.out.println(“6”);
  }
}


class C  extends B {
  static {
      System.out.println(“7”);
  }
  {
      System.out.println(“8”);
  }
  C(){
      System.out.println(“9”);
   }
}


The output of the statement A a=new C(); is:
    1
    4
    7 
    2
    3  
    5 
    6  
    8 
    9 
  • 1 4 7 belong to static blocks: static blocks are called at startup
  • 2 belongs to A instance block: instance blocks are called each time an object is constructed
  • 3 belongs to A constructor
  • 5 belongs to B instance block: instance blocks are called each time an object is constructed
  • 6 belongs to B constructor
  • 8 belongs to C instance block: instance blocks are called each time an object is constructed
  • 9 belongs to C constructor
A constructor is called before the B constructor and B constructor is called before the C constructor because we don't have to forget that each time a constructor is invoked, the java virtual machine goes to inizialize the superclass constructor.

No comments :

Post a Comment

Suggested Pages