File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Polymorphism in Overloaded and Overridden Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Polymorphism in Overloaded and Overridden Methods" Watch "Polymorphism in Overloaded and Overridden Methods" New topic

Polymorphism in Overloaded and Overridden Methods

Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
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.


Naseem Khan
[ May 30, 2006: Message edited by: Naseem Khan ]

Asking Smart Questions FAQ - How To Put Your Code In Code Tags
luo luo
Ranch Hand

Joined: Dec 09, 2003
Posts: 36
because in the Animal, only the method eat(Object o) defined, there is no such method as eat(String s) in the base class.

Let it snow~
tapan saha

Joined: May 15, 2006
Posts: 17
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"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.
I agree. Here's the link:
subject: Polymorphism in Overloaded and Overridden Methods
It's not a secret anymore!