This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes overriding and polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "overriding and polymorphism" Watch "overriding and polymorphism" New topic
Author

overriding and polymorphism

Dan Craciun
Greenhorn

Joined: Dec 03, 2011
Posts: 11
Hi

I have the following question:
Given the code below :



The output is:

foo in Child(Parent)
foo in ParentFunction
*******************
foo in ChildFunction
*******************
foo in Child(Parent)
foo in ParentFunction
*******************
foo in Child(Parent)
foo in Child(Parent)
foo in Child(Parent)

StackOverflowError.

I’m OK with the output of the first three method calls

Why is the method foo(Parent) from Child instead of foo(Parent) from Parent gets called at the fourth line generating a recursive call?
My understanding is that there is no polymorphism here, so in this case we should have early binding.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Dan Craciun wrote:
Why is the method foo(Parent) from Child instead of foo(Parent) from Parent gets called at the fourth line generating a recursive call?
My understanding is that there is no polymorphism here, so in this case we should have early binding.


And where exactly did that "understanding" come from? The foo(Parent) is certainly a polymorphic method. Your code test proves that to be the case and your statements in your post show that you can see it is the case. So the only problem is that "understanding" of yours, which you need to explain.
Dan Craciun
Greenhorn

Joined: Dec 03, 2011
Posts: 11
Hi,

I'm will skip the other method calls:

we have:

Child f = new Child();
Parent g = f;

On the third method call - g.foo(new Parent()); we have polymorphism

But on the fourth g.foo(new Child()); there is no method in Parent class - foo(Child); so why do we have polymorphim here ?
Isn't the call resolved at compile time?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You have polymorphism because all overridden methods are always polymorphic. And yes, what's resolved at compile time is that the method to be used is foo(Parent), because -- as I think you might have been trying to say -- that's the only possibility. What happens at run time is that the polymorphism comes into play, as it always does.
Dan Craciun
Greenhorn

Joined: Dec 03, 2011
Posts: 11
Got it !
Thank you Paul
 
 
subject: overriding and polymorphism
 
Similar Threads
synthetic classes
Polymorphism (invoking methods) - K&B book.
same method inheritance
Why call int version,not char version?
Overriding/overloading