Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Q from Sahir's Testcafe

 
Amanda Fu
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1561
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Andres! It's clear!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic