SuperClass object = new SubClass();
Why use a superclass to instantiate a subclass object like above? Because the only way i learnt to instantiate an object is to:
SubClass object = new SubClass();
I'm learning java.
If a superclass is defined in a path of the inheritance tree using the addition CREATE PRIVATE, outside consumers cannot instantiate a subclass, and a subclass cannot even instantiate itself, because it has no access to the instance constructor of the superclass.
Yes, the super class reference variable can hold the sub class object actually, it is widening in case of objects (Conversion of lower datatype to a higher datatype).
Therefore, if you assign an object of the subclass to the reference variable of the superclass then the subclass object is converted into the type of superclass and this process is termed as widening (in terms of references).
When declaring a variable in a subclass with the same name as in the superclass, you are hiding the variable, unlike methods which are overwritten.
You may have a method that only takes an instance of SuperClass
. Since SubClass
is a SuperClass
, you can use an instance of SubClass
and treat it as SuperClass
.
The same behavior is used when working with interfaces:
List someList = new ArrayList();
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.
This is known as polymorphism. Imagine the following example:
Musician musician = new Pianist();
or
Musician musician = new Drummer();
Suppose Musician
class has a method: play()
. It doesn't matter who the musician is, if you call play method, you'll know how to play the determined instrument, base on concrete class, on this case, no matter if Pianist or Drummer.
Each concrete class, overwriting its play()
method, can play on your own:
e.g. for Pianist
class: play() { playsBeethoven(); }
For detailed information, please check http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
It's always good to remember to use it with inheritance http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With