Reputation: 63
In my code two classes are there ,subclass extends superclass.In sub class i override superclass method. On the time of object creation i created superclass reference to sub class object its working fine. But again i converted super class reference to complete super class object but it calls sub class methodn not super class method. My assumption the output is wrong.Here my code
public class OverRiding {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Super class reference to sub class Object
Dog dog = new Animal();
dog.eat();
dog.bow();
//Completely converted into pure Dog class Object
Dog d = (Dog) dog;
d.eat();
d.bow();
}
}
Dog class
class Dog {
public void eat() {
System.out.println("Dog eat Biscuits");
}
public void bow() {
System.out.println("Dog bow");
}
}
Class Animal
class Animal extends Dog {
public void eat() {
System.out.println("Animal eat Food");
}
}
And my output is
Animal eat Food
Dog bow
Animal eat Food
Dog bow
Upvotes: 0
Views: 11933
Reputation: 36304
Your concept is not correct bro...
class Animal extends Dog
How can Animal extend a dog? . Its like saying - "EVERY ANIMAL IS A DOG" . Which is wrong... So, it should be the other way around...
This example will only confuse you further..
Donno why nobody brought this up...
Upvotes: 5
Reputation: 17048
You assumption is false:
Completely converted into pure Dog class Object
When you are casting your Animal
to a Dog
, your variable d is still an Animal
. It is also a Dog
, but the most specific type is Animal
.
You are not completely converted your variable to another instance. Your instance is still the same.
For a proof, you can try this code :
Dog d = (Dog) dog;
d.getClass(); // output Animal
Upvotes: 1
Reputation: 121998
Dog dog = new Animal();
//Completely converted into pure Dog class Object
Dog d = (Dog) dog;
Both Dog
and d
are pointing to the same reference, Since you are not creating a new object
. Cast won't have an effect here.
Casting and Creating is completely different.
Upvotes: 2
Reputation: 79818
In this example, you've only created one object, and it's an Animal
, (which sadly, is a special type of Dog
). When you call eat
on this object, you're always going to get the version defined in the Animal
class, not the version defined in the Dog
class.
That's polymorphism. The version of the method that gets called depends on the class of the object, not the type of the variable that refers to it.
Upvotes: 1
Reputation: 6988
Dog d = (Dog) dog;
Here d
is not pure Dog
object. It's still of Animal
type. Pure Dog
object would be created via Dog d = new Dog()
.
Upvotes: 3