0
Why reference variable is of different type than the object type
Sometimes reference variable of parent class refers to the child class object. Why it is done and what is the use of it when reference variable type and object type can be same i.e. either of parent class type or child class type Example Animal myanimal= new Cat(); where Animal is parent class and Cat is child class.
5 Respuestas
+ 1
That depends from your objects structure. When for you project will better to spcialize the parent class with a few child classes. So you can extend the class with new properties / methods as well as overwritte existing methods with more suitable code for the child class.
+ 1
Basically:
Animal foo = new Cat();
Gives foo everything from Animal but nothing specific to Cat
Cat foo = new Cat();
Gives foo everything from Animal and Cat.
Edit: both will give you methods from Animal that are overridden in Cat
0
Yeah, I have same doubt.
0
https://code.sololearn.com/c7J9r2F6dRSN/?ref=app
Maybe this helps.
Try using
Animal catAni = new Cat();
catAni.onlyChild();
And see what happens