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.

8th Mar 2022, 2:17 PM
Krishna Kumar
Krishna Kumar - avatar
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.
8th Mar 2022, 2:34 PM
JaScript
JaScript - avatar
+ 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
8th Mar 2022, 2:40 PM
Brave Tea
Brave Tea - avatar
0
Yeah, I have same doubt.
8th Mar 2022, 2:31 PM
kev_coding
kev_coding - avatar
0
https://code.sololearn.com/c7J9r2F6dRSN/?ref=app Maybe this helps. Try using Animal catAni = new Cat(); catAni.onlyChild(); And see what happens
8th Mar 2022, 2:48 PM
Brave Tea
Brave Tea - avatar