• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

overridden and overloading question

 
Ranch Hand
Posts: 264
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everybody, i have one doubt regarding following question.

class Animal {
void eat(Object o){
System.out.println("In Animal Object");
}
}

class Horse extends Animal{
void eat(Object o){
System.out.println("In Horse Object");
}

void eat(String str){
System.out.println("In Horse String");
}
}

public class Test {
public static void main(String[] args){
Animal a=new Horse(); // Line 1
a.eat("grass"); // Line 2
}
}

Output is "In Horse Object"...

As we are calling the method with string parameter, so void eat(String str) of Horse should be called.

Please explain that actual concept behind this.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because a is a reference of type Animal, the compiler is going to look for the method eat in Animal. Since eat(Object o) is overridden in the subclass Horse, and Horse is the runtime type of the object referred to by a, the method eat(Object o) in Horse is going to be called.
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try this instead. You need to override the String version of the function to achieve the expected result.

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic