1

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.

Community
  • 1
  • 1
HelloWorld
  • 123
  • 1
  • 12

1 Answers1

2

When you create an instance of SubClass

SuperClass superClass = new SubClass();

you can cast superClass to SubClass and gain access to the methods of SubClass. You can't do it when you create an instance of SuperClass.

In addition, calling methods of SuperClass on an instance of SubClass would execute SubClass methods when SubClass overrides these methods.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks for quick answer. Appreciated. – HelloWorld Dec 06 '15 at 07:28
  • Could you please explain in which situation would I require casitng `superClass` object to `SubClass` so that I can access `SubClass'` methods, because if I know that I will require `SubClass` object in advance then I will use `SubClass` object instead of `SuperClass`? – HelloWorld Dec 07 '15 at 12:53