Win a copy of Rust Web Development this week in the Other Languages 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
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

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.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic