• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

another thread from Dan's mock exam

 
Kelvin Mak
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {
A() {
System.out.println("CA");
}
{
System.out.println("IA");
}
static {
System.out.println("SA");
}
}
class Test extends A {
Test() {
System.out.println("CB");
}
{
System.out.println("IB");
}
static {
System.out.println("SB");
}
public static void main(String[] args) {
new Test();
}
}
Dan , would you tell me why? thx
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why what?
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again this is how I summerized Dan's explanation on this topic:
On instantiating an object of a certain type, the static initializers of the super classes are executed first starting with the highest class in the hierarchy, then the static initializer of the class of the object itself is executed.
Then because of an implicit or explicit super() call in the subclass constructor, the instance initializers and the constructors of the super classes are executed in couples (instance initializer & constructor of each class) also starting with the highest class in the heirarchy then at the end the instance initializer and constructor of the class of the object itself are executed.
* Instance initializers are always executed before the constructors.
* If there is more than one block of static initializers in the body of the class, they are executed according to the order they appear in the class body. Using variables - that are declared in a later initializer - in an earlier one will cause a compile time error. Same goes for inistance initializers.
HTH
[ October 15, 2002: Message edited by: Alfred Kemety ]
[ October 15, 2002: Message edited by: Alfred Kemety ]
 
Kelvin Mak
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you, Alfred Kemety.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic