I Knew there are plenty of articles/questions in stackoverflow describing about upcasting and downcasting in Java. And I knew what is upcasting and downcasting. But my question is not specfic to that.
Upcasting - Conversion from child to parent - Compiler takes care. No cast is required
Downcasting - Conversion from parent to child - Explicit cast is required
public class Animal {
public void getAnimalName(){
System.out.println("Parent Animal");
}
}
public class Dog extends Animal{
public void getDogName(){
System.out.println("Dog");
}
}
public static void main(String[] args) {
Dog d = new Dog();
Animal a = d; // Upcasting
a.getAnimalName();
Animal vv = new Dog();
Dog cc = (Dog)vv;//DownCasting
cc.getAnimalName();
cc.getDogName();
If you look into the Animal
and Dog
class, each are having their own methods like getAnimalName()
and getDogName()
. Hence Dog extends Animal
(is-a relationship), so we can use the base class(Super Class) methods in the derived class(Subclass)
Consider the below piece of code in the Main Method now,
So here I'm creating a Dog
object w.rt Animal
. So I can be able to access only the Animal
properties(Methods)
Dog d = new Dog();
Animal a = d; // Upcasting
a.getAnimalName();<br>
O/P : Parent Animal<br><br>
Now Let's say, I would like to override the base class methods into the derived class
public class Dog extends Animal{
@Override
public void getAnimalName(){
System.out.println("Parent Animal overridden here");
}
public void getDogName(){
System.out.println("Dog");
}
}<br>
And in Main Method,
Dog d = new Dog();
Animal a = d; // Upcasting
a.getAnimalName();<br>
O/P : Parent Animal overridden here<br><br>
Even though I'm creating a Dog
object w.r.t Animal
, but here it is printing the base class method which is overridden in the dervied class.
O/P : Parent Animal overridden here<br>
Wondering why it behaves like this. Is this becasue of the override
?
Please provide your valuable input's.