This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method from constructor

 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! Why my code



gives output

Derived.amethod() --- why? "Base.amethod()" expected
99
Derived.amethod()

Base constructor can't know anything about it's children.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Andry Dub:
Base constructor can't know anything about it's children.


You're right, it doesn't. But thanks to the magic of polymorphism, the Base constructor's call to amethod() will be bound at runtime to the overridden implementation in Derived. In fact, this doesn't only apply to constructors; this is true of any call by a Base method to another Base method, unless the latter cannot be overridden (e.g. if it's final or private).

Among other things, this mechanism allows the use of the template design pattern in Java.
 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Kelvin! It is very valuable information for me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic