Reputation: 121
I have troubles to understand, why class A constructor outputs 41, class B constructor outputs 40 in this case below
class AK {
AK(int i) {
System.out.println("Cstr of A " + i);
}
AK(){
System.out.println("Cstr of A()");
}
}
class BK extends AK {
BK(int i) {
super(i+1);
System.out.println("Cstr of B " + i);
}
BK(){
System.out.println("Cstr of B()");
}
}
class CK extends BK {
CK(int i) {
super(2 * i);
System.out.println("Cstr of C " + i);
}
}
class Main {
public static void main (String args[]) {
new CK(20);
}
}
output:
Cstr of A 41
Cstr of B 40
Cstr of C 20
Upvotes: 0
Views: 38
Reputation: 114
In main()
method when you create object of CK, jre invokes constructor chaining which will call main() -> CK(20) -> BK(40)-> AK(41).
When you call CK(20) constructor, it calls super(2i)=BK(int i)=BK(40) constructor with value 2i=2*20. When BK(int i) constructor is called with value 40, it calls super(i+1)=AK(int i)=AK(41) with value i+1=40+1.
Since you are printing value i in BK() and not i+1, it does print 40 instead of 41.
Upvotes: 0
Reputation: 2767
In main()
you create an object CK with an integer 20 as parameter. The constructor of CK is calling its super constructor of BK with 2 * parameter (= 40). The constructor of BK is also calling its super constructor with parameter + 1 ( = 41).
And each constructor is printing its value of the integer parameter. The constructor is printing its result first because it is the first constructor that gets finished since the other constructors are calling it.
calling CK constructor with parameter 20 => i = 20
calling BK constructor with i * 2 => i = 40
calling AK constructor with i + 1 => i = 41
Also i is never reassigned so its value stays in the other constructor just as it is.
Upvotes: 2