Java – why use superclass references for objects?
See English answers > What does it mean to "program to an interface"? 32
public class Musician { public void play() { // do something } }
.
public class Drummer extends Musician { public void turnsDrumStick() { // do something } }
.
public class Guitarist extends Musician { public void strummingStrings() { // do something } }
I can use polymorphism to do the following:
Musician m1 = new Guitarist(); Musician m2 = new Drummer(); m1 = m2;
However, I can't see the methods of subclasses:
m1.strummingStrings(); //COMPILATION ERROR!
If I use:
Guitarist m1 = new Guitarist();
Isn't it better? What are the benefits of using musico type to reference subclass objects? It's just possible that I can put M1 = m2; Attributed to? Or are there other advantages?
I read this article, but I am still confused: using superclass to initialize a subclass object Java
Solution
When you can call play () on any musician, whether it's a guitarist, drummer, or any other subclass of musicians you may not have created, the advantage of polymorphism comes
Musician m1 = new Guitarist(); Musician m2 = new Drummer(); m1.play(); m2.play();
This may produce similar results
Guitarist strumming Drummer drumming
If you override the play () method in two subclasses In this way, the code calling play () does not need to know which implementation of music it is actually, but it is a musician and is guaranteed to have a play () method
Calling subclass methods (such as strummingStrings) from multiple class references is not an advantage of polymorphism, because this method exists only in subclasses. It is not guaranteed to exist in superclasses If you need to call subclass only methods (such as strummingstring), you need a subclass reference
You can define strummingstrings in superclass musicians, and polymorphism will work, but it will be a bad design Not all musicians can play string music on the guitar