This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Calling overridden methods from a constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic

Calling overridden methods from a constructor

Andrew Keidel

Joined: Dec 06, 2001
Posts: 27
I think this question is an interesting one.
Imagine this situation:
1. We have a class Base with public method makeReady().
2. Base calls makeReady() from within its constructor.
3. We make a class Derived that extends Base and overrides the makeReady() method.
My question is this: What happens when we try: "Derived d = new Derived();"? More specifically, when the constructor in Derived calls Base's constructor (which is always done because Base is its parent class), Base's constructor calls the makeReady() method... who's makeReady() method does it call?
If you think the answer is obviously that in this case, Derived's makeReady() method is called by Base's constructor, you may be right about the answer (I'm not sure), but you're wrong that it's obvious. In C++, the above scenario does NOT work this way. Instead, in C++, when Base's constructor is called through Derived's constructor, the virtual makeReady() method call in Base's constructor will use Base's own makeReady() method.
I don't understand why this happens in C++, and I don't know what happens in Java. It's easy enough to test this out with code, but what I'm more curious about is the REASON why each language works the way it does.
Here is a link to the C++ explanation, which I don't fully understand:
Help, please! Thanks!
Stelian Iancu

Joined: Feb 20, 2002
Posts: 21
Well, my opinion is that the Base's makeReady() method is called. Why? Because the constructor of Base doesn't know anything about Derived. So there is no polymorphism involved here.
As written in the article you gave the link for, the objects are constructed from the base up, so when Base's constructor is called, there is no Derived object (after all, that is what we are doing, constructing a Derived object).
Hope this helps!

--<br />Linux registered user 287835<br /> <br />Be different. Think.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
You kind of stuttered this question. Please continue the conversation here

"JavaRanch, where the deer and the Certified play" - David O'Meara
It is sorta covered in the JavaRanch Style Guide.
subject: Calling overridden methods from a constructor