This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism in Overloaded and Overridden Methods

 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

Can any one plz explain why the actual method called at runtime is the overriding method of Horse class.



Output of above code is:

In Horse Object

A similar question is discussed in K & B book under the heading "Polymorphism in Overloaded and Overridden Methods" on page 109, but with slight difference. Instead of eat(Object) signature, the Animal class defines following signature...

public void eat(){...}

Code below....



This code is clear to me. Here at line 2, compilation error will come coz eat(String) is not defined in Animal class. Whereas in my case, since eat(Object) is defined in Animal class and String can be promoted to Object so no compilation error will come in my code.

My question is why the overriding method called at runtime in first case.

Thanks

Naseem Khan
[ May 30, 2006: Message edited by: Naseem Khan ]
 
luo luo
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because in the Animal, only the method eat(Object o) defined, there is no such method as eat(String s) in the base class.
 
tapan saha
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Naseem,
let me explane in details.

Original Code base: Start

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 Whiz1 {
public static void main(String[] args){
Animal a=new Horse(); // Line 1
a.eat("grass"); // Line 2
}
}
Original Code base: End


See in whiz class, you create instance of Horse() which is associated with class Animal. You will get only those methods which is define in Animal but contain will be overwrite thing in Horse if it is overwritten.

See you are calling eat at line 2 with string parameter which is also a Object. So it is calling method void eat(Object o) with overwrite contain.

Hope it will help you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic