Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic