Understanding the three major characteristics of Java polymorphism (iii)

Source: Internet
Author: User

Excerpt from: http://cmsblogs.com/?p=52

  

Object-oriented programming has three main features: encapsulation, inheritance, polymorphism.

Encapsulation hides the internal implementation mechanism of the class, which can change the internal structure of the class without affecting the usage, and also protects the data. For the outside world its internal details are hidden and exposed to the outside world just by its access methods.

Inheritance is to reuse the parent class code. Two classes you can use inheritance if there is a is-a relationship. , and inheritance is also a foreshadowing for realizing polymorphism. So what is polymorphism? What is the implementation mechanism of polymorphism? Please look at my one by one to uncover for you:

The so-called polymorphism refers to the specific type of reference variable defined in the program and the method call issued by the reference variable is not determined during programming, but is determined during the program's run, that is, the instance object that refers to the class to which the variable is inverted. The method call that the reference variable emits is exactly the method that is implemented in the class that must be determined by the time the program is run. Because when the program is run to determine the specific class, so that, without modifying the source code, you can bind the reference variable to a variety of different class implementations, resulting in the invocation of the specific method of the reference change, that is, do not modify the program code can be changed when the program runs the specific code, so that the program can select multiple running state, This is polymorphism.

For example, you are a wine God, have a unique feeling for wine. Some day home found a few cups inside are loaded with white wine, from the outside to see we can not know what this is what wine, only after drinking to be able to guess what kind of wine. You drink, this is Jiannanchun, drink again this is wuliangye, again drink this is alcoholic wine .... Here we can describe it as follows:

Wine A = Jiannanchun

Wine B = Wuliangye

Wine c = Alcoholic drink

...

What we are doing here is polymorphism. Jiannanchun, Wuliangye, alcoholic wine are the sub-class of wine, we just through the wine this one parent can refer to different subclasses, this is polymorphic-we can only run when we know the reference variable point to the specific instance object.

Admittedly, to understand polymorphism we have to understand what is "upward transformation". In the inheritance we briefly introduced the upward transformation, here is the wordy: in the above drinking example, wine (Win) is the parent class, Jiannanchun (JNC), Wuliangye (wly), alcoholic wine (JGJ) is a subclass. We define the following code:

JNC a = new JNC ();

For this code we are very easy to understand is to instantiate a Jiannanchun object! But what about this?

Wine a = new JNC ();

Here we understand that a wine type of a, which points to an Jnc object instance, is defined here. Since Jnc is inherited from wine, Jnc can automatically move up to wine, so a can point to Jnc instance objects. There is a great benefit in this, as we know in inheritance that subclasses are extensions of the parent class, that it can provide more powerful functionality than the parent class, and that if we define a reference type that refers to the parent class of a subclass, it can also use the subclass's powerful functionality in addition to referencing the generality of the parent class.

However, there are some drawbacks to the upward transformation, which is that it will inevitably lead to the loss of some methods and properties, which leads us not to acquire them. So a reference to a parent class type can call all the properties and methods defined in the parent class, which is no more than 1 for methods and properties that exist only with subclasses.

public class Wine {public    void fun1 () {        System.out.println ("The fun of Wine ...");        Fun2 ();    }        public void Fun2 () {        System.out.println ("Wine of Fun2 ...");}    } public class JNC extends wine{    /**     * @desc Subclass Overloaded Parent class Method     *        The method is not present in the parent class, and the parent class cannot refer to the method after it has been transformed.     * @param a     * @return void     *    /public void fun1 (String a) {        System.out.println ("JNC Fun1 ...");        Fun2 ();    }        /**     * Subclass overriding Parent class method     * When referring to a subclass's parent class reference called Fun2, the method must be called     */public    void Fun2 () {        System.out.println ("JNC Fun2 ... ");}    public class Test {public    static void Main (string[] args) {        Wine a = new JNC ();        A.fun1 ();    }} -------------------------------------------------output:wine Fun ... JNC's Fun2 ...

From the running results of the program we find that A.fun1 () first runs the fun1 () in the parent class wine. Then run fun2 () in subclass Jnc.

Analysis: In this program the neutron class JNC overloaded the parent wine Method Fun1 (), Overrides Fun2 (), and the overloaded fun1 (String a) and fun1 () are not the same method, because there is no such method in the parent class, the method is lost after the upward transformation, So the wine type reference that executes JNC is not referenced by the FUN1 (String a) method. When the subclass Jnc overrides Fun2 (), the wine reference to JNC calls the Fun2 () method in Jnc.

So for polymorphism we can summarize as follows:

a parent class reference to a subclass because it has been transformed upward, it can only access methods and properties that are owned in the parent class, and the reference is not available for methods that exist in the subclass and that do not exist in the parent class, although the method is overloaded. If subclasses override some of the methods in the parent class, they must be called using the methods defined in the subclass (dynamic joins, dynamic calls).

For object-oriented, polymorphism is divided into compile-time polymorphism and run-time polymorphism. When editing the polymorphism is static, mainly refers to the method of overloading, it is based on the parameter list to distinguish between different functions, by editing will become two different functions, at runtime is not polymorphic. While the runtime polymorphism is dynamic, it is implemented by dynamic binding, which is what we call polymorphism.

Multi-State implementation

2.1 Implementation Conditions

In the beginning, it was mentioned that inheritance was prepared for polymorphic implementations. Subclass Child inherits the parent class father, we can write a reference to the parent class type of the child class, which can handle either the parent class Father object or the subclass child object, when the same message is sent to the child class or the parent class object. The object performs different behavior depending on the reference to which it belongs, which is polymorphic. That is, polymorphism is the same message that makes different classes respond differently.

There are three prerequisites for implementing polymorphism in Java: inheritance, rewriting, and upward transformation.

Inheritance: Subclasses and parent classes that have inheritance relationships must exist in polymorphism.

Rewrite: Subclasses redefine some methods in the parent class and call the methods of the subclasses when they are called.

Upward transformation: In polymorphic, a reference to a subclass needs to be assigned to the parent class object, so that the reference can have the ability to invoke methods and subclasses of the parent class.

Only by satisfying the above three conditions can we use uniform logic implementation code in the same inheritance structure to handle different objects, thus achieving different behavior.

For Java, its polymorphic implementation mechanism follows a principle: when a superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the quilt class overrides the method.

2.2 Realization Form

There are two forms of polymorphism that can be implemented in Java. Inheritance and interfaces.

2.2.1, multi-state based on inheritance implementation

The implementation mechanism based on inheritance mainly manifests in the rewriting of some methods by the parent class and one or more subclasses inheriting the parent class, and the rewriting of the same method by many subclasses can show different behavior.

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 is" + getName ();    }/** * Overrides ToString () */public String tostring () {return null;    }}public class JNC extends wine{public JNC () {setName ("JNC");    }/** * Overrides the parent class method, implementing Polymorphic */Public String drink () {return "drink is" + getName ();    }/** * Overrides ToString () */public String tostring () {return ' Wine: ' + getName ();    }}public class Jgj extends wine{public jgj () {setName ("jgj");    }/** * Overrides the parent class method, implementing Polymorphic */Public String drink () {return "drink is" + getName ();    }/** * Overrides ToString () */public String tostring () {return ' Wine: ' + getName (); }}public class Test {public static void main (string[] args) {//Define parent classArray wine[] wines = new Wine[2];        Define two subclasses JNC JNC = new JNC ();                Jgj jgj = new jgj ();        Parent class reference 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--Drink is jncwine:jgj--drink is jgj-------------------------------

In the above code, JNC, jgj inherit wine, and rewrite the drink (), toString () method, the program run result is called the method in the subclass, output Jnc, jgj name, this is the performance of polymorphism. Different objects can perform the same behavior, but they all need to be implemented in their own way, thanks to an upward transformation.

We all know that all classes inherit from the superclass Object,tostring () method is also the method in object, when we write this:

Object o = new Jgj ();      System.out.println (O.tostring ());

The result of the output is wine:jgj.

Object, Wine, jgj three inheritance chain relationship is: Jgj->wine->object. So we can say this: When a subclass overrides a method of the parent class is called, only the least-end method in the object's inheritance chain is called. but note that if you write this:

Object o = new Wine (); System.out.println (O.tostring ());

The result of the output should be null, because JGJ does not exist in the inheritance chain of the object.

So the polymorphism based on inheritance can be summed up as follows: for a parent class type that references a subclass, when the reference is processed, it applies to all subclasses that inherit the parent class, the subclass object is different, the implementation of the method is different, and the behavior that occurs with the same action is different.

If the parent class is an abstract class, then the subclass must implement all the abstract methods in the parent class, so that all subclasses of the parent class must have a unified external interface, but the concrete implementations within it can vary. This allows us to use the uniform interface provided by the top-level class to handle the method at that level.

2.2.2, multi-state based on interface implementation

Inheritance is manifested by overriding several different subclasses of the same method of the parent class, which can be realized by implementing the interface and overwriting several different classes of the same method in the interface.

In polymorphic interfaces, a reference to an interface must be an instance program that specifies a class that implements the interface, executing the corresponding method at run time, based on the actual type of the object reference.

Inheritance is a single inheritance and can only provide a consistent service interface for a set of related classes. But the interface can be multi-inheritance multi-implementation, it can use a set of related or irrelevant interfaces for combination and expansion, can provide a consistent service interface. So it has better flexibility than inheritance.

Third, the classic example.

through the above, can be said to have a certain understanding of polymorphism. Now take the strike and see an example. This example is a classic example of polymorphism, excerpted 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 ("n" + 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)); }}

Operation 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 to see results 1, 2, 3 good understanding, starting from 4 began to be confused, for 4 why output is not "B and B" it?

First, let's take a look: When a Superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the quilt class overrides the method. This statement is a generalization of polymorphism. in fact, the invocation of an object method in the inheritance chain has a priority: 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, D has the following relationship.

First we analyze 5,a2.show (c), A2 is a reference variable of type A, so this represents the A,a2.show (c), it found in Class A is not found, so to a super Class (super), because a no superclass (except object), so jump to the third level, That is This.show (Super) O, the superclass of C has B, a, so (Super) O is B, A,this is also a, where show (a obj) is found in a, and since A2 is a reference to Class B and Class B overrides show (a obj), Therefore, the show (A obj) method of subclass Class B is eventually called, and the result is B and A.

I can also confirm other answers in the same way.

The method has been found. But we still have a question here: When a Superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, This means that the quilt class overrides the method. We use an example to illustrate what this sentence means: A2.show (b);

Here A2 is a reference variable, a type, it refers to the B object, so according to the above sentence means that there is a B to decide who to call the method, so A2.show (b) should call B in the show (b obj), the resulting result should be "B and B", But why is it different from the results of the previous operation? Here we ignore the following sentence "but the method called here must be defined in the superclass", so does show (B obj) exist in Class A? It doesn't exist at all! So this is not a valid sentence here? So is this the wrong sentence? Not too! In fact, this sentence also implies that this sentence: it still has to follow the inheritance chain to invoke the priority of the method to confirm. So it will find show (a obj) in Class A, and the method in Class B is called because B overrides the method, otherwise the method in Class A is called.

Therefore, the principle of polymorphic mechanism is summarized as follows: When a superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the quilt class overrides the method, However, it still needs to confirm the method based on the priority of the method invocation in the inheritance chain, which is: This.show (o), Super.show (O), This.show (Super) O, Super.show ((Super) O).

References: http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx .

Baidu Library: http://wenku.baidu.com/view/73f66f92daef5ef7ba0d3c03.html

Understanding the three major characteristics of Java polymorphism (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.