Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference Variable Casting?

 
Hennry Smith
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



When we try to compile this code, the compiler says something like this:
cannot find symbol
The compiler is saying, "Hey, class Animal doesn't have a playDead() method".
Let's modify the if code block:
if(animal instanceof Dog) {
Dog d = (Dog) animal; // casting the ref. var.
d.playDead();
}




Please explain i am not able to understand this concept...???
 
Abhinav Yadav
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is happening because the class Animal is a super class and it has only one method and that is
and Dog is its subclass ,its simple to explain that why compiler shows error it is because when object of Dog is created in
it is stored in reference of type Animal
and in case of function overriding it depends upon the reference variable used to call the function and not upon the object it is storing.
Since there is no function named playDead() in the class Animal thus error is shown.
 
Vidya sumanasekara
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This happens because of the overriding...

In the supper class Animal -> void makeNoise()

In the sub class Dog-> void makeNoise()//overriden method & playDead()// this is unique for this class

Then you have assining a dog instance to the Animal reference ( in the loop)

In that case compiler check
Animal animal=new Dog();
first reference type (Animal) where there is playDead() method and runtime check the instance type. ok..
In your case there is no any method playDead() in Animal class..so compiler gives an error..

Hennry Smith wrote:


When we try to compile this code, the compiler says something like this:
cannot find symbol
The compiler is saying, "Hey, class Animal doesn't have a playDead() method".
Let's modify the if code block:
if(animal instanceof Dog) {
Dog d = (Dog) animal; // casting the ref. var.
d.playDead();
}




Please explain i am not able to understand this concept...???
 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1. This statement says: I don't care what array of animals you give me as long as they are "Animal". Because I just want to use them as "Animal", if they have special gifts , then save them for their girl friends.


2. And when I say "Animal", I mean they can makeNoise().


3. When I write this, Java compiler complains: hey, boss, you either make "Animal" can playDead(), or accept the reality by correcting this statement.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic