Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Super class constructor calls derived class overridden method?

 
Paul Jacob
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Sheriff
Pie
Posts: 48954
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jason Irwin
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic