• Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphism not working as expected  RSS feed

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this while experimenting with code, where a parent reference variable refers to a subclass. I wonder if anyone could give a pointer as to what is happening in the following code, as I'm finding a situation in which the parent version of a method runs rather than the child version.

What I would have expected from the following code is either a compile or a runtime error (on grounds that the subclass method is private). However, what I actually found is that the parent method runs in both cases, which I wouldn't have expected at all.

In other words, if it ran at all, I'd expect the output to be:

Parent class ribbet
Child class ribbet

What I'm actually getting is:

Parent class ribbet
Parent class ribbet

I do understand that this code doesn't constitute an override, as the private method in the parent class would not be inherited. However, I had thought that only static methods of the parent class would be invoked in this kind of situation.

I'd guess it's probably just a blue moon situation, but can anyone shed any light on why this behaviour occurs?

 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paddy Howard wrote:I do understand that this code doesn't constitute an override, as the private method in the parent class would not be inherited.

Correct, there is no overriding, which means, from a Frog reference there is no attempt to find a method in a child class. So the question comes down to method visibility. Is Frog's ribbet() method visible to the main method? Why or why not? What would happen if the main method were in the Spawn class? Or in a different class altogether?

However, I had thought that only static methods of the parent class would be invoked in this kind of situation.

You have an instance of a Frog, and so can call instance methods from it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!