Win a copy of OCP Oracle Certified Professional Java SE 11 Developer Practice Tests this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
Sheriffs:
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
Bartenders:
  • Carey Brown
  • salvin francis
  • Piet Souris

Basic question about Overload/Override

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Why this code outputs "Animal"? Can you explain? Is it a case of overloading instead override?
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 59
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
And then the flying monkeys attacked. My only defense was this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic