Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method from constructor