Thursday 8 September 2011

Sequence in which static initialization block, initialization block, constructors are called


1.Static initialization blocks are called even if object of that class in never created. If class which has a Static initialization blocks is having any relation(isA/hasA) directly or indirectly with the main class, than Static initialization blocks is called.Static initialization blocks are called first. Very Super Class Static initialization blocks are called, than its subclass Static initialization blocks are called and so on...
2.initialization blocks are called before constructor means before any object of that class is created and after Static initialization blocks.
3.Subclass constructor has its 1st statement either call to super() or this(), but not both. By default super() is called if nothing is specified. If you have defined no constructor in your class , than by default compiler inserts a no arg constructor in your class . If you have defined a constructor in your class , than compiler will not insert any constructor in your class. That is if you have defined arg constructor , than you will have to define no arg constructor ,dont expect compiler to define for you. 




Here is a program than shows sequence in which  static initialization block, initialization block, constructors are called
This is important concepts for those who is preparing for scjp exam and also for those who are working as core java developer.


class
A {
{ System.out.print("b1 "); }
public A() { System.out.print("b2 "); }
}

class B extends A {
static { System.out.print("r1 "); }
public B() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}

public class Test9 extends B {
public static void main(String[] args) {
System.out.print("pre ");
new Test9();
System.out.println("post ");
}
}
output:
r1 r4 pre b1 b2 r3 r2 post

Please comment if you find my article helpful.

No comments:

Post a Comment