This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: overridden and overloading question
 
Similar Threads
overloaded method call rules
Overloaded question
over loaded methods??
Polymorphism in Overloaded and Overridden Methods
overload and override method question