Consider the following code snippet:
SuperClass superClass = new SubClass(); // Instantiating SuperClass reference
SubClass subClass = new SubClass(); // Instantiating SubClass reference
If I list fields/methods of superClass
object, I can see methods from SuperClass only. Then what's the difference between:
SuperClass superClass = new SubClass();
and
SuperClass superClass = new SuperClass();
I know it could be a case of polymorphism and I can use SubClass
reference, as SubClass
IS-A SuperClass
, but why would I use SubClass
reference if I want to instantiate SuperClass
as I'm getting the same fields/methods by instantiating it with SuperClass
?
I've seen this question but I'm still confused. Using superclass to initialise a subclass object java
Edit: I am not talking about interfaces here. I know about interfaces that we can use them to assign objects of the classes that implements them. I'm talking about only superclass.
Any help on this would be appreciated.