+ 6

a superclass reference variable can refer to a subclass object , but what is it's practical use?

Checked many websites ,stackoverflow ,books but I can't really understand this concept. ●1.we can simply use a subclass reference for using a subclass object.so why use base class reference? ●2.well every tutorial/book etc says runtime polymorphism is powerful feature but how? why do we even need it? it's "slower" than compile time polymorphism. I haven't found any source that "really" explains why they call it "powerful". One more thing that is often told "flexibility". what does it even mean in this context? ●3.what really makes it unable to happen at compile time ? why methods of subclass called upon base class reference can't be resolved at compile time? All these questions arise because of this : " a superclass reference variable can refer to a subclass object ". Only use I know is that both super and sub class objects can be stored in an array of type super class. That's all. Where have you used elsewhere? ~ swim ~ , John Wells , David Carroll , Shadow 🙏

7th Dec 2019, 5:17 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
3 Respuestas
+ 2
Taste thanks I'll read that. Avinesh , Super class reference can invoke sub class version of methods that are present in superclass and overridden by sub class. What you said is also valid, we can't invoke superclass methods through super class reference unless we have method with same signature in super class to override them in subclass. As you know this isn't what I asked btw. I wanted know in particular why do we even use super class reference as sub class reference can do work. I appreciate your help :) Thanks again.
7th Dec 2019, 6:12 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Not sure how relevant it is, I'm just sharing my view on this. When we create a reference to the super class and create an instance of the subclass, the object can invoke only the members defined in the super class. If at all some object doesn't need any new behaviour added by the subclass then isn't that useful that we give the reference of superclass.
7th Dec 2019, 5:48 PM
Avinesh
Avinesh - avatar