Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding and polymorphism

 
Dan Craciun
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it !
Thank you Paul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic