wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Refrence type or Instance type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Refrence type or Instance type" Watch "Refrence type or Instance type" New topic
Author

Refrence type or Instance type

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
class Animal{
public void eat(){
System.out.println("I m in Animal");
}
}


class Horse extends Animal{
public void eat(){
System.out.println(" I m in Horse");
}
}

public class first{

public static void main(String[] args){
Animal a=new Animal();
Animal b=new Horse();
a.eat();
b.eat();
}
}

Dear Sir in the prciding code i have taken two refrence a and b of type Animal. In b i m assigning the object of type Horse that's why b.eat() is calling the horse version of eat.
But on the other hand it has been written in Book K and B on page 101 that "The compiler looks only the refrence type , not the instance type" then if this then b is a refrence type of Animal then why it is calling the Horse version of eat()?

withe Regard

Arun kumar maalik
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Arun Maalik:

But on the other hand it has been written in Book K and B on page 101 that "The compiler looks only the refrence type , not the instance type" then if this then b is a refrence type of Animal then why it is calling the Horse version of eat()?


Because the compiler doesn't decide which version to call - it just checks that it is guaranteed the object will have *some* implementation for the method (->static type checking). Which exact method is called is decided at runtime by the virtual machine (->polymorphism).


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Refrence type or Instance type
 
Similar Threads
Which eat method and why ??
static or dynamic ..why
the complier looks only at the reference type not the instance type for overridden methods!!???!!
which version of method is actually called ? the reference one or actual object one ?
method overriding