Polymorphism separates the interface from the implementation by separating "what" and "How to do" from another perspective. The role of polymorphism is to eliminate the coupling between types, and polymorphic method invocations allow a type to exhibit differences from other similar types as long as they are derived from the same base class.
1. Pass in the base class in the method parameter, make the subclass easy to call
Classinstrument{PublicvoidPlay (Note N) {System.out.println ("Instrument.play ()")); }}Class WindExtendsinstrument{PublicvoidPlay (Note N) {System.out.println ("Wind.play ()" +N); }}class music{ public static void tune (instrument i) // parameter is base class {I.play (note.c_charp);}
public
static void main (string[] args) {Wind flute = new Wind (); Tune (flute); // Direct incoming subclass Wind }}enum note{meddle_c, C_charp, B_flat;}
2. Method call binding (not quite understood, first logged, later in the study: )
(1) Associating a method invocation with the same method body is called a binding;
(2) Pre-binding: Binding before program execution, implemented by compiler and linker.
(3) Late binding: Binds to the object type at run time. Also known as "dynamic binding" or "runtime binding".
In addition to the static method and the final method in Java (the private method belongs to the final method), all other methods are late-bound. Declaring a method as final is primarily a way to effectively "close" dynamic bindings.
3. Another usage scenario for polymorphism
class music{ Public static void tune (instrument i) // parameter is the base class {I.play (note.c_charp);} public static voidnew Wind (); Tune (flute) ; //new Wind (); Tune (i); }}
In creating a subclass instance, you can use this method:instrument i = new Wind (); , I see a reference to the parent class, but actually initialize the subclass.
Note: When the parent method permission is private, the method of overriding the parent class is invalid, that is: two methods are different (even if the method name is the same)
Classsuperclass{PrivatevoidFuntion () {System.out.println ("superclass.funtion ()"); }PublicvoidFuntion2 () {System.out.println ("superclass.funtion () public"); }PublicStaticvoidMain (string[] args) {Superclass sup =new subclass (); Sup.funtion (); Sup.funtion2 ();}} class subclass extends// @Override //----plus Error He method funtion () of type subclass must Override or implement a Supertype method public void Funtion () {System.out.println ("subclass.funtion ()" public void Funtion2 () {System.out.println (" Subclass.funtion2 () public "); }}
Output Result:
Superclass.funtion ()
Subclass.funtion2 () public
Conclusion:
(1) Because the parent class method cannot be overridden, the funcion () of the parent class superclass is called when it is called
(2) Therefore, if you override the parent class method, the parent class's method is defined as public.
Java Learning Note Six: polymorphic