"Java Basics" polymorphism

Source: Internet
Author: User

First, let's start with a summary:

What is polymorphic

    1. Object-oriented three major features : encapsulation, inheritance, polymorphism. From a certain point of view, encapsulation and inheritance are almost always prepared for polymorphism. This is our last concept, but also the most important point of knowledge.
    2. polymorphic definition : means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call)
    3. the technique of implementing polymorphism is called dynamic binding, which is the actual type of the referenced object that is judged during execution, and its corresponding method is called according to its actual type.
    4. the role of polymorphism: to eliminate the coupling relationship between types.
    5. in reality, there are numerous examples of polymorphism. For example, if you press the F1 button, if the current pop-up in the Flash interface is the as 3 help document, if Word Help is currently popping up under Word, Windows Help and Support appears under Windows. The same event occurs on different objects and produces different results.

Here are the three necessary conditions for polymorphic existence, requiring you to recite them in a dream!

Three necessary conditions for polymorphic existence
First, to have inheritance;
Second, to have a rewrite;
The parent class reference points to the subclass object.

Benefits of polymorphism:

1. Replaceable (substitutability). Polymorphism is replaceable for existing code. For example, polymorphism works on the Circle Circle class and works on any other circular geometry, such as a ring.
2. expandability (Extensibility). Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, and the operation and manipulation of other attributes of existing classes. In fact, new subclasses are more likely to get polymorphic functions. For example, it is easy to add the polymorphism of sphere class on the basis of realizing the multi-state of cone, semi-cone and hemispherical body.
3. Interface (interface-ability). Polymorphism is a superclass that, by way of signature, provides a common interface to subclasses, which is implemented by subclasses to refine or overwrite the class. As shown in 8.3. The super-Class shape in the figure specifies two interface methods for implementing polymorphism, Computearea () and Computevolume (). Subclasses, such as circle and sphere, refine or overwrite both interface methods in order to achieve polymorphism.
4. Flexibility (flexibility). It embodies the flexible operation in the application, and improves the use efficiency.
5. Simplification (simplicity). Polymorphism simplifies the process of coding and modifying the application software, especially when dealing with the operation and operation of a large number of objects.


The implementation of the polymorphic in Java: 1 interface Implementation 2 inherits the parent class, makes the method override 3 the same class in the method overload.

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, and it is no more than a---1 for methods and properties that exist only with subclasses.

 Public classMain { Public Static voidMain (string[] args) {Wine a=NewJNC ();    A.fun1 (); }}classWine { Public voidfun1 () {System.out.println ("The fun of Wine ...");    Fun2 (); }         Public voidfun2 () {System.out.println ("The Fun2 of Wine ..."); }}classJNCextendswine{/*** @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 .@paramA *@returnvoid*/     Public voidfun1 (String a) {System.out.println ("JNC Fun1 ...");    Fun2 (); }        /*** Subclass overriding Parent class method * When referring to a subclass's parent class reference when calling Fun2, the method must be called*/     Public voidfun2 () {System.out.println ("JNC Fun2 ..."); }}
-----------------
Output:wine's 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 classWine {PrivateString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicWine () {} PublicString Drink () {return"The Drink is" +GetName (); }        /*** Rewrite ToString ()*/     PublicString toString () {return NULL; }} Public classJNCextendswine{ PublicJNC () {SetName ("JNC"); }        /*** Override the parent class method to implement Polymorphic*/     PublicString Drink () {return"The Drink is" +GetName (); }        /*** Rewrite ToString ()*/     PublicString toString () {return"Wine:" +GetName (); }} Public classJgjextendswine{ Publicjgj () {SetName ("Jgj"); }        /*** Override the parent class method to implement Polymorphic*/     PublicString Drink () {return"The Drink is" +GetName (); }        /*** Rewrite ToString ()*/     PublicString toString () {return"Wine:" +GetName (); }} Public classTest { Public Static voidMain (string[] args) {//defining an array of parent classesWine[] Wines =NewWine[2]; //define two subclassesJNC JNC =NewJNC (); Jgj jgj=Newjgj (); //Parent class referencing child class objectWines[0] =Jnc; wines[1] =jgj;  for(inti = 0; I < 2; i++) {System.out.println (wines[i].tostring ()+ "--" +Wines[i].drink ()); } System.out.println ("-------------------------------"); }}output:wine:jnc--the drink is jncwine:jgj.--the 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 classA { PublicString Show (D obj) {return("A and D"); }     PublicString Show (A obj) {return("A and a"); } } Public classBextendsa{ PublicString Show (B obj) {return("B and B"); }         PublicString Show (A obj) {return("B and A"); } } Public classCextendsb{} Public classDextendsb{} Public classTest { Public Static voidMain (string[] args) {A A1=NewA (); A A2=NewB (); b b=NewB (); C C=NewC (); D d=NewD (); System.out.println ("+"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).

"Java Basics" polymorphism

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.