Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Basic question about Overload/Override

 
Front Enista
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why this code outputs "Animal"? Can you explain? Is it a case of overloading instead override?
 
Rahul Saple
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method eat() in class Animal is private and hence is not visible outside of the class(including any subclasses). The eat method of the subclass (Horse) doesn't override the superclass' method as it isn't inherited by the class.
It just has the same name which is what makes it confusing.
 
Rahul Saple
Ranch Hand
Posts: 46
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, the polymorphic behavior of the reference 'a' would come into picture only if the method was overridden. Changing the signature of the eat method in the superclass to anything but private would give you the desired result.
The way you have defined the method is neither overloading nor overriding.
 
John Pradeep.v
Ranch Hand
Posts: 59
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can remember the logic behind this behvior by understanding the bytecode generated.
for normal method call, the compiler generates an "invoke" instruction which resolves the target class type at runtime... however, when a private method is called the compiler generates an "invokespecial" instruction which doesnt try to resolve the target method based on the instance type.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic