Using superclass to initialise a subclass object java [duplicate]

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