• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Overloading/Overriding Problem

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello ranchers,

Here this code:


Outputs:
Mammal eats food

My first question is: Is eat() being overridden or overloaded? Arguments in subclasses are subclasses of those argument defined in superclasses.

I understand that c.eat(h) attaches it to mammal's version at compile time because of reference variable, but at runtime doesn't it know that the object held is of type horse. Since class Cattle doen't have eat(horse), it should have invoked eat(cattle).

Thanks in advance

Deepak
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To override a method, the arguments must not change. Passing an argument which is a subtype is still a change in the argument. Therefore what you have is a case of overloading--NOT overriding. Which overloaded method is called is, as you point out, determined by the compiler at compile time. There is no overriding going on for the JVM to go picking a different method at run time.
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Deepak,
this is a nice question. The answer is Overload.

The expanded version of the classes is ...

if don't believe it then try marking the methods final the code will still compile!! if the methods were overriden then marking them final will give compile errror.
Good luck for your exam!
 
Deepak Bajoria
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, thank you Jamie and Milan for your explanations, got that.
 
There are 10 kinds of people in this world. Those that understand binary get this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic