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 Q from Sahir's Testcafe 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 "Q from Sahir Watch "Q from Sahir New topic
Author

Q from Sahir's Testcafe

Amanda Fu
Ranch Hand

Joined: Jul 17, 2003
Posts: 31
Following is one question from Sahir's Testcafe Mock Exam, I'm always confused with such questions, at runtime, use eat(Mammal) or eat(Horse)? I have gone though Mughal's book, but didn't read things concerns it. I hope to make it clear completely, please give me a link concerns this topic. Thanks!
class Mammal{
void eat(Mammal m){
System.out.println("Mammal eats food");
}
}
class Cattle extends Mammal{
void eat(Cattle c){
System.out.println("Cattle eats hay");
}
}
class Horse extends Cattle{
void eat(Horse h){
System.out.println("Horse eats hay");
}
}
public class Test{
public static void main(String[] args){
Mammal h = new Horse();
Cattle c = new Cattle();
c.eat(h);
}
}
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
trick question hey?
My $0.02

1o) All these classes have the same method name, but with different parameter type, therefore is overloading.
2o) Now that we now is overloading, we must check the reference type and not the object type
3o) c.eat(h);
Since it is the reference type (in this case "c), we should look at the Cattle class:

but in reality, the class Cattle looks like this

The method void eat(Mammal m) is inherited from class Mammal because of this:
class Cattle extends Mammal
So, if we say
c.eat(h);
We passing a reference to a Mammal to our Cattle class, so the method that receives a Mammal as a parameter is invoked, printing out Mammal eats food.
Hope this helps
[ July 18, 2003: Message edited by: Andres Gonzalez ]

I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
From KnB book

1o) Object type determines which overriden method is used at runtime
2o) Reference type determines which overloaded method will be used at compile time.

In your example, since it is an overload, we follow point number 2o)
Amanda Fu
Ranch Hand

Joined: Jul 17, 2003
Posts: 31
Thanks Andres! It's clear!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Q from Sahir's Testcafe
 
Similar Threads
output
Inheritance doubt
polymorphism
Output........?
explain the flow of the program