wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method from constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Method from constructor" Watch "Method from constructor" New topic
Author

Method from constructor

Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
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.


Java is my love
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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.


SCJP 5.0
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Thank you, Kelvin! It is very valuable information for me.
 
Don't get me started about those stupid light bulbs.
 
subject: Method from constructor
 
Similar Threads
Mock Exam question.
How is this??
Inheritance/Polymorphism question
inheritance question
Doubt in Mock Question