wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Super class constructor calls derived class overridden method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Super class constructor calls derived class overridden method?" Watch "Super class constructor calls derived class overridden method?" New topic
Author

Super class constructor calls derived class overridden method?

Paul Jacob
Greenhorn

Joined: Jul 25, 2009
Posts: 15
Hi, Here is a piece of code and its output. Could not understand why the derived class method is called:



When we run this, the output is:

In ctr of Test1()
In Test2.d()
In ctr of Test2()
2

My questions is -
Why did Test2.d() get called from the ctr of Test1()? And if it did, then why is the value of i printed as 2 and not 5?

Please reply asap.
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
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.

Change the code for Test2 to this:Does that help?


SCJP6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37926
    
  22
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.
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
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?)

I quickly found out I was wrong though!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
Thanks Rob!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Super class constructor calls derived class overridden method?
 
Similar Threads
Compilation fails
Inheritance and protected methods
instanceof question?
error in result
Understanding inheritance