Java - Upcasting and Downcasting

♀尐吖头ヾ 提交于 2019-12-04 18:12:06

When you refer your subclass with parent class, method call on reference pointer calls the subclass method.

Dog d = new Dog();
Animal a = d; // Upcasting
a.getAnimalName();

Here a.getAnimalName(); calls the subclass's getAnimalName() method, as it is inherited from base class, so the parent class's method is called. It is not directly called on base class, rather through subclass's inheritance. When you override, it is instantly invoked from subclass, it does not need to go to parent class to check the existence of the method.

But a side note is that base class reference can't call methods on subclass, which are not defined in base class.

Animal a = d; 

this line will make your Animal object 'a' point to the instance of Dog class (Dog d = new Dog();). Therefore when you call the function it will invoke the function in class dog.

You actually created an instance of class Dog Dog d = new Dog();. Then you are making an object of class Animal and making it point to the instance of class Dog Animal a = d;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!