It's actually part of one interview question I got confused.
class A
{
public A()
{
System.out.println("A") ;
}
}
class B extends A
{
public B()
{
System.out.println("B") ;
}
}
A a1 = new B();
System.out.println() ;
A a2 = (A) new B() ;
So the question is what is the print out?
At first I thought it should print out like
B
A
B
A
But after I run at home, it gives
A
B
A
B
I understand it's inheritance and then upcasting B to A, and it's legal syntax as well, but why is A print before B?
why is A print before B?
Because the body of the superclass constructor is executed before the body of the subclass constructor, basically.
Think of your B()
constructor as implicitly:
public B()
{
super(); // This invokes A's constructor
System.out.println("B") ;
}
The full details are in JLS 12.5. In particular:
This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using
this
). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (usingsuper
). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps.
See more on this question at Stackoverflow