This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
d() is overridden in Test2. When the JVm executed the method "d()" on the object in the heap, it is an instance of Test2 that is there, so it is the method on Test2 that is executed.
That explanation may not be the best.
That is an example of a potentially dangerous vulnerability. Any methods called from the constructor should be "private" or "final". Then that method could not be overridden, and that problem wouldn't occur.
Joined: Jun 09, 2009
The thing that I had forgotten was when "i" gets initialised. For some reason I thought that happened before the invocation of the A constructor (as to invoke that, via the implicit "super()", surely the constructor of B has been entered and to get into that, variable have initialsed?)
Variable initialization occurs between the call to super and any code you put in the constructor. That's why i is 2: it starts at 0, is set to 5 by the call to d(), then is set to 2 by the initializer.