This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Innvocation - overridden or overloaded

 
Simon Cockayne
Ranch Hand
Posts: 214
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

RE: The "Java 2" book by Kathy Sierra & Bert Bates, Chapter 5, page 311.

Given...

public class Horse extends Animal {
eat(){}
eat(String){}
}
public classAnimal {
eat(){}
}

Table 5-3 explains that if a method is overloaded then the "Reference Type" of the object determines which overloaded version is run. Whereas if the method is overridden then the "Object Type" determines which method is selected.

Logically, if an object invokes eat(), since the method is overridden, then the object type at run time determines whether to invoke the Animal.eat() or the Horse.eat(). Contrariwise, if an object invokes eat(String), since the method is overloaded the reference type at compile time determines the method signature.

BUT...suppose...Animal also has eat(String){}

public class Horse extends Animal {
eat(){}
eat(String){}
}
public classAnimal {
eat(){}
eat(String) {} //This has been added...
}

Now, is eat(string) overridden or overloaded or both? How do I calculate whether Horse.eat(String) or Animal.eat(String) is run?

Cheers,

Simon.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case, Java chooses the method signature at compile time based on the overloading rules and chooses the specific method of that signature at run time using the overriding rules.
 
Aruna Agrawal
Ranch Hand
Posts: 66
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

is eat(string) overridden or overloaded or both? How do I calculate whether Horse.eat(String) or Animal.eat(String) is run?


BOTH
 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes , it is overloding & overriding both . But the method will be called beased on object type ( At run time ) .

Aminal aOb = new Horse();
aOb.eat("Grass");

In this case , eat(String) method of Horse class will be called .
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic