Understanding the polymorphism of java's three major features (3) and java's three major feature Polymorphism
From: http://cmsblogs.com /? P = 52
Object-Oriented Programming has three main features: encapsulation, inheritance, and polymorphism.
The internal implementation mechanism of the class is hidden. The internal structure of the class can be changed without affecting the usage, and the data is also protected. Its internal details are hidden, and only its access method is exposed to the outside world.
Inheritance is used to reuse the parent code. If two classes have a IS-A relationship, you can use inheritance ., Inheritance also paves the way for polymorphism. So what is polymorphism? What is the implementation mechanism of polymorphism? Please refer to the steps I will unveil for you:
The so-called polymorphism refers to the specific type pointed to by the referenced variable defined in the program and the method call made through the referenced variable are not determined during programming, but are determined only during the program running, that is, the Instance Object of the class to which a referenced variable directs. The method called by the referenced variable must be determined by the program running. This is because the specific class is determined only when the program is running, so that reference variables can be bound to different class implementations without modifying the source code, as a result, the specific method of the Reference call changes accordingly, that is, without modifying the program code, you can change the specific code bound to the program running, so that the program can select multiple running states, which is polymorphism.
For example, you are a wine God and have a special liking for wine. One day I went home and found that there were several cups Containing liquor on the table. From the outside, we could not know what kind of liquor it was. Only after drinking could we guess what kind of wine it was. When you drink, this is jiannanchun, this is Wuliangye, and then this is a liquor .... Here we can describe as follows:
Wine a = jiannanchun
Liquor B = Wuliangye
Liquor c = Liquor
...
What is shown here is polymorphism. Jiannanchun, Wuliangye, and liquor are sub-classes of liquor. We can reference different sub-classes only through the parent class of liquor, this is polymorphism-we only know the specific instance object that the referenced variable points to when running.
To understand polymorphism, we must understand what is "upward transformation ". In inheritance, we briefly introduced the upward transformation. Here we are talking about it: in the above drinking example, Win is the parent class, JNC, and WLY) JGJ is a subclass. The following code is defined:
JNC a = new JNC ();
For this code, we can easily understand that it is nothing more than instantiating an object of jiannanchun! But what about it?
Wine a = new JNC ();
Here, we understand that a Wine type a is defined, which points to the JNC object instance. Because JNC is inherited from Wine, JNC can be automatically transformed to Wine, so a can point to the JNC instance object. In this way, there is a great benefit. In inheritance, we know that the subclass is an extension of the parent class, which can provide more powerful functions than the parent class, if we define a parent class reference type pointing to a subclass, it can not only reference the common characteristics of the parent class, but also use the powerful functions of the subclass.
However, there are some shortcomings in the upward transformation, that is, it will inevitably lead to the loss of some methods and attributes, and we will not be able to obtain them. Therefore, the reference of the parent class can call all the attributes and methods defined in the parent class. For methods and attributes that only exist in the Child class, it cannot reach-1.
Public class Wine {public void fun1 () {System. out. println ("Wine Fun ..... "); fun2 ();} public void fun2 () {System. out. println ("Wine Fun2... ") ;}} public class JNC extends Wine {/*** @ desc subclass overload parent class Method * this method does not exist in the parent class, the parent class is * @ param a * @ return void */public void fun1 (String a) {System. out. println ("JNC Fun1... "); fun2 ();}/*** subclass override parent class Method * when the parent class reference pointing to the subclass calls fun2, it must call this method */public void fun2 () {System. out. println ("JNC Fun2... ") ;}} public class Test {public static void main (String [] args) {Wine a = new JNC ();. fun1 () ;}----------------------------------------------------- Output: Wine Fun ..... JNC Fun2...
From the running results of the program, we found that a. fun1 () first runs fun1 () in Wine of the parent class, and then runs fun2 () in JNC of the subclass ().
Analysis: In this program, the subclass JNC reloads the fun1 () method of the parent Wine class, overwrites fun2 (), and reloads fun1 (String a) and fun1 () not the same method. Because the parent class does not have this method, this method will be lost after the upward transformation. Therefore, the fun1 (String a) method cannot be referenced when the Wine type reference of JNC is executed. The subclass JNC overrides fun2 (), so the Wine reference pointing to JNC will call the fun2 () method in JNC.
We can summarize the polymorphism as follows:
Since the parent class reference pointing to the subclass is transformed upwards, it can only access the methods and attributes in the parent class, but for methods that exist in the subclass but do not exist in the parent class, this reference is not usable, although it is a heavy load of this method. If the subclass overrides some methods in the parent class, these methods (dynamic connection and dynamic call) must be used to call these methods defined in the subclass ).
For object-oriented objects, polymorphism can be divided into polymorphism during compilation and Runtime polymorphism. The polymorphism during editing is static and mainly refers to method overloading. It distinguishes different functions based on different parameter lists. After editing, it becomes two different functions, there is no polymorphism at runtime. The Runtime polymorphism is dynamic, which is achieved through dynamic binding, that is, what we call polymorphism.
Implementation of Polymorphism
2.1 Implementation Conditions
At the beginning, we mentioned that inheritance is preparing for the implementation of polymorphism. Child of the subclass inherits the parent class Father. We can write a reference to the parent class of the subclass. This reference can process both the parent class Father object and the Child class object, when the same message is sent to a subclass or parent class object, the object performs different behaviors based on its own reference. This is a polymorphism. That is, polymorphism means that the same message makes different classes make different responses.
Java Implementation polymorphism has three necessary conditions: inheritance, rewriting, and upward transformation.
Inheritance: In polymorphism, subclasses and parent classes with inheritance relationships must exist.
Override: subclass re-defines some methods in the parent class. When these methods are called, The subclass method is called.
Upward Transformation: In polymorphism, You need to assign the reference of the subclass to the parent class object. Only in this way can this reference be able to call the methods and subclass methods of the parent class.
Only when the above three conditions are met can we use a unified logic in the same inheritance structure to implement code to process different objects, so as to execute different behaviors.
For Java, its implementation mechanism of polymorphism follows the principle that when a superclass object references a variable to reference a subclass object, the type of the referenced object, rather than the type of the referenced variable, determines who calls the member method. However, the called method must have been defined in the superclass, that is, the method overwritten by the quilt class.
2.2 Implementation form
There are two forms of polymorphism in Java. Inheritance and interfaces.
2.2.1 inheritance-based Polymorphism
The inheritance-based implementation mechanism is mainly manifested in the rewriting of some methods by the parent class and one or more sub-classes that inherit the parent class, rewriting of the same method by multiple subclasses may show different behaviors.
Public class Wine {private String name; public String getName () {return name;} public void setName (String name) {this. name = name;} public Wine () {} public String drink () {return "drink" + getName () ;}/ *** override toString () */public String toString () {return null;} public class JNC extends Wine {public JNC () {setName ("JNC ");} /*** override the parent class method to implement polymorphism */public String drink () {return "drink" + getName () ;}/ *** override toString () */public String toString () {return "Wine:" + getName () ;}} public class JGJ extends Wine {public JGJ () {setName ("JGJ ");} /*** override the parent class method to implement polymorphism */public String drink () {return "drink" + getName () ;}/ *** override toString () */public String toString () {return "Wine:" + getName () ;}} public class Test {public static void main (String [] args) {// define the parent class array Wine [] wines = new Wine [2]; // define two subclasses JNC jnc = new JNC (); JGJ jgj = new JGJ (); // The parent class references the subclass object wines [0] = jnc; wines [1] = jgj; for (int I = 0; I <2; I ++) {System. out. println (wines [I]. toString () + "--" + wines [I]. drink ();} System. out. println ("-----------------------------");} OUTPUT: Wine: JNC -- JNCWine: JGJ -- JGJ -------------------------------
In the above Code, JNC and JGJ inherit Wine and overwrite the drink () and toString () methods. The program running result is to call the methods in the subclass and output the names of JNC and JGJ, this is the manifestation of polymorphism. Different objects can execute the same behavior, but they all need to execute it in their own implementation mode, which will benefit from the upward transformation.
We all know that all classes are inherited from the superclass Object, and the toString () method is also the method in the Object. When we write this:
Object o = new JGJ(); System.out.println(o.toString());
The output result is Wine: JGJ.
The inheritance links of Object, Wine, and JGJ are: JGJ-> Wine-> Object. So we can say this: when a subclass override parent class method is called, only the last method in the Object Inheritance chain will be called. Note:
Object o = new Wine();System.out.println(o.toString());
The output result should be Null because JGJ does not exist in the inheritance chain of this object.
So the polymorphism Based on inheritance implementation can be summarized as follows: for the parent class type of the reference subclass, when processing the reference, it applies to all the subclasses that inherit the parent class, the subclass object is different, the implementation of methods is different, and the Behavior Produced by executing the same action is also different.
If the parent class is an abstract class, the subclass must implement all the abstract methods in the parent class, so that all the child classes of the parent class must have a unified external interface, however, the specific internal implementation can be different. In this way, we can use the unified interface provided by the top-level class to process the methods at this level.
2.2.2 interface-based Polymorphism
Inheritance is embodied by rewriting several different sub-classes of the same method of the parent class, so it can be embodied by implementing the interface and overwriting several different classes of the same method in the interface.
In interface polymorphism, the reference to the interface must be an instance program that specifies this interface to implement a class. At runtime, execute the corresponding method based on the actual type referenced by the object.
Inheritance is a single inheritance and can only provide consistent service interfaces for a group of related classes. However, interfaces can be multi-inherited and multi-implemented. They can be combined and expanded using a set of related or unrelated interfaces to provide consistent external service interfaces. Therefore, it is more flexible than inheritance.
3. Classic instances.
Through the above description, we can say that we have a certain understanding of polymorphism. Now let's take a look at an instance. This is a classic example of polymorphism, from http://blog.csdn.net/thinkghoster/archive/2008/04/19/2307001.aspx.
public class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } }public class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } }public class C extends B{}public class D extends B{}public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println("1--" + a1.show(b)); System.out.println("2--" + a1.show(c)); System.out.println("3--" + a1.show(d)); System.out.println("4--" + a2.show(b)); System.out.println("5--" + a2.show(c)); System.out.println("6--" + a2.show(d)); System.out.println("7--" + b.show(b)); System.out.println("8--" + b.show(c)); System.out.println("9--" + b.show(d)); }}
Running result:
1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D
Here, we can see that results 1, 2, and 3 are easy to understand. They have been confused since 4. Why is the output not "B and B" for 4?
First, let's take a look at one sentence: When a super-Class Object references a variable to reference a subclass object, the type of the referenced object, instead of the type of the referenced variable, determines who calls the member method, however, the called method must have been defined in the superclass, that is, the method covered by the quilt class. This sentence summarizes polymorphism. In fact, there is a priority for calling object methods in the inheritance chain: this. show (O), super. show (O), this. show (super) O), super. show (super) O ).
Analysis:
From the above procedure, we can see that A, B, C, and D have the following relationships.
First, we will analyze 5, a2.show (c), and a2 are the referenced variables of the type. Therefore, this indicates A, a2.show (c), which is not found in Class, so find (super) in the superclass of A, because A does not have A superclass (except for objects), so jump to level 3, that is, this. show (super) O), C has B, A, so (super) O is B, A, this is also, show (A obj) is found in A, and because a2 is A reference of class B and class B overrides show (A obj ), therefore, the show (A obj) method of subclass B will be called, and the result is B and.
I can confirm other answers in the same way.
The method has been found, but we still have some questions here. Let's look at this sentence: When a super Class Object references a variable to reference a subclass object, the type of the referenced object, rather than the type of the referenced variable, determines who calls the member method. However, the called method must have been defined in the superclass, that is, the method overwritten by the quilt class. Here we use an example to illustrate the meaning of this sentence: a2.show (B );
Here a2 refers to the reference variable, which is of the type and references the B object. Therefore, according to the above sentence, B is used to determine which method to call, therefore, a2.show (B) should call show (B obj) in B, and the result should be "B and B". But why is it different from the previous running results? Here we ignore the following sentence "but the method called here must be defined in the superclass". does show (B obj) exist in Class? It does not exist at all! So this sentence is not applicable here? So is this sentence wrong? None! In fact, this sentence also implies this sentence: it should still be confirmed according to the priority of the method called in the inheritance chain. So it will find show (A obj) in Class A, and B will call the method in Class B because it overwrites the method. Otherwise, it will call the method in Class.
So the principle of polymorphism mechanism is summarized as follows: When a super Class Object references a variable to reference a subclass object, the type of the referenced object rather than the type of the referenced variable determines who calls the member method, however, the called method must have been defined in the superclass, that is, the method covered by the quilt class, but it still needs to confirm the method based on the priority of the method call in the inheritance chain, this priority is: this. show (O), super. show (O), this. show (super) O), super. show (super) O ).
Reference: http://blog.csdn.net/thinkghoster/archive/2008/04/19/2307001.aspx.
Baidu: http://wenku.baidu.com/view/73f66f92daef5ef7ba0d3c03.html