Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Refrence type or Instance type

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic