I am having problems after the "path" of the code after the line new B (). If someone can explain every step after calling B (), then it would be highly appreciated.
When calling new B() stream technically enters the constructor of B() . Java designers always need (ultimately) a chain to a higher constructor (recursively until they reach the highest Object class). The chain is indicated by the super(...) or this(...) operator as the first constructor statement. If not one of them is written explicitly, the imperceptible super() assumed. So, B() really compiles, as if it were written as follows:
public B() { super(); setI(20); System.out.println("i from B is " + i); }
Now you can clearly see that new B() calls B() , which calls A() (which calls println and exits), then setI and finally println .
Why is int i in B completely different from i in A?
i is the exact same field. The difference comes from the fact that you called setI(20) between two printouts, thereby changing the value of i . If you delete the call on setI , you will see that the value remains 7 .
Theodoros Chatzigiannakis
source share