Because, 1. Parent class is loaded before the child class. 2. When a class is loaded static-blocks are executed first + static variables are initialized to defaults + instance variables are set to their default values. 3. Constructor of parent class is first executed before the execution of the child class constructor.
First case :: class Bird { { System.out.print("bl "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); System.out.println("hawk "); } }
OutPut r1 r4 pre hawk
Second Case:::
class Bird { { System.out.print("bl "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } }
output :: r1 r4 pre bl b2 r3 r2 hawk
Third case :::
class Bird { { System.out.print("bl "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk { public static void main(String[] args) { System.out.print("pre "); new Raptor (); System.out.println("hawk "); } }
Output :::
pre r1 r4 bl b2 r3 r2 hawk
Deepak Vadgama
Greenhorn
Joined: Jul 02, 2007
Posts: 29
posted
0
The static block of code is called, when the classes are loaded, in the same order as they appear in the source code
The code
is called, initializer block (without the static keyword)
The Java compiler copies initializer blocks into every constructor. Thus it becomes part of constructor, called only when a Object is created, and not when a class is loaded.