• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Refrence type or Instance type

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
reply
    Bookmark Topic Watch Topic
  • New Topic