File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overridden and overloading question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overridden and overloading question" Watch "overridden and overloading question" New topic
Author

overridden and overloading question

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Feb 24, 2006
Posts: 6661
    
    5

Try this instead. You need to override the String version of the function to achieve the expected result.



SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: overridden and overloading question