posted 24 years ago
Hi quan,
Whenever an object is created with the "new" keyword,a call is made to the constructor.
If the object has any superclasses,then a call is immediately made to the superclass constructor and this goes on until we go all the way up the inheritance hierarchy.
Say ,there is just one superclass,then when the superclass constructor is called
1)
a)if the superclass has any initalizer block,then that is executed first and then the constructor is executed.
b)The initializer block in the subclass is executed and then the subclass constructor is executed.
2)If the Superclass itself has some static initializers then that is executed first before everything else (i.e. even before the static initializers of the subclass) and then the static initializers of the subclass are executed,followed by Initializers and so on and so forth.......
So the order can be put as follows:
Superclass:Static Decl
Superclass:Static Block
Subclass:Static Decl
Subclass:Static Block
Superclass:Initializer
Superclass:Constructor
Subclass:Initializer
Subclass:Constructor
For example:-
------------
class bb{
static {
String superstaticvar= "e";
System.out.println("super static value=" + superstaticvar);
}
String initvar = "a";
{ initvar = "d";
System.out.println("super initializer value =" + initvar);
}
bb(){
System.out.println("Inside super constr");
}
}
public class InitTest extends bb
{
static String s1 = sM1("a");
{ s1 = sM1("b"); }
static
{s1 = sM1("c"); }
public static void main(String args[ ] )
{
InitTest it = new InitTest( );
}
public InitTest()
{
System.out.println("Inside sub constr");
}
private static String sM1(String s) {
System.out.println(s) ; return s;
}
}
Hope all this makes sense
-Yeggy
Yeggy<br />Sun Certified Programmer for Java2 Platform