File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overridden and overloading question

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • 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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic