JAVA polymorphism from shallow and deep introduction _java

Source: Internet
Author: User
Tags inheritance

What is polymorphism?

Polymorphism is divided into two types:

(1) Compile-time polymorphic (design-time Polymorphism): Method overload.

(2) Run-time polymorphism: The Java runtime system determines which method is called Run-time polymorphism based on the type of the instance that invokes the method. (we usually speak much of the things in the Run-time polymorphism, so polymorphic mainly refers to the run-time polymorphism)

Three necessary conditions for Run-time polymorphism:
First, must have the inheritance (including the interface realization);
Second, to have to rewrite;
Third, the parent class reference points to the child class object.


--------------------------------------------------------------------------------

Detailed Explanation:

Run-time polymorphism Interpretation: A. Run-time polymorphism refers to the specific type and b that the reference variable defined in the program points to. The method call issued through the reference variable is not determined programmatically, but is determined during the run of the program, where a reference variable will point to the instance object of which class, and the method called by the reference variable is the method that is implemented in which class. Must be determined by the time the program is run.

1. The specific type of reference variable defined in the sequence is indeterminate (that is, a reference variable will point to the instance object of which class).

Example:

Drive method in driver Class (Vehicle class vehicle) {}

onedriver.drive (new Car ())
onedriver.drive (New Bus ())
Where the vehicle variable cannot determine exactly which subclass instance to use.

1. A method call issued through the reference variable is not determined programmatically (the method invoked by the reference variable is the method implemented in the class).

Example: The Cut method Call of the chef, Gardener, Barber. Persion.cut ().


--------------------------------------------------------------------------------

The benefits of polymorphism:

1. interchangeability (substitutability). polymorphic pairs of existing code are replaceable. For example, polymorphic pairs of circular circle work on any other circular geometry, such as rings, also work.

2. Extensibility (Extensibility). Polymorphic is extensible for code. Adding new subclasses does not affect the polymorphism of existing classes, inheritance, and the operation and operation of other features. In fact, the new subclass is more likely to get polymorphic functionality. For example, in the realization of the cone, half cone and hemispherical body on the basis of polymorphism, it is easy to add the sphere of the polymorphism of the class.

3. Interface (interface-ability). Polymorphism is a superclass that is implemented by means of a method signature that provides a common interface to subclasses to refine or overwrite. As shown in Figure 8.3. The superclass shape in the figure prescribes two interface methods for implementing polymorphism, Computearea () and Computevolume (). Subclasses, such as circle and sphere, to implement polymorphism, perfect or overwrite these two interface methods.

4. Flexibility (flexibility). It embodies the flexible and various operation in the application, and improves the usage efficiency.

5. Simplification (simplicity). Polymorphism simplifies the process of coding and modifying the code of application software, especially in dealing with the operation and operation of a large number of objects, which is especially important.

Practical application:

Combined with the use of configuration files, contact the spring framework, use reflection, dynamic call classes, without modifying the source code, directly add new classes and modify configuration files, do not need to restart the server to expand the program.


--------------------------------------------------------------------------------

Summary:

Object that uses the reference of the parent class type to the subclass. This reference invokes the method and variable defined in the master class, the variable cannot be overridden (overwritten), and if one of the methods in the parent class is overridden in the subclass, the method in the subclass is invoked when the method is called;

Note that in special cases, if the parent class references the method argument list that is invoked is not defined, it calls the parent class for the lookup, and if it is not found, forces the type of the parameter in the UP type conversion argument list, with a high to low precedence, in order of the following:

This.show (o), Super.show (O), This.show (Super) O), Super.show ((Super) O).


--------------------------------------------------------------------------------

Classic Pen questions (mixed overloads and overrides):

(i) Related classes

Copy Code code as follows:

Class A {
Public String Show (D obj) ... {
Return ("A and D");
}
Public String Show (A obj) ... {
Return ("A and a");
}
}
Class B extends a{
Public String Show (B obj) ... {
Return ("B and B");
}
Public String Show (A obj) ... {
Return ("B and A");
}
}
Class C extends B ... {}
Class D extends B ... {}

(ii) Question: What are the following output results?

A a1 = new A ();
A A2 = new B ();
b b = new B ();
c C = new C ();
D d = new D ();
System.out.println (A1.show (b)); ①
System.out.println (A1.show (c)); Ii
System.out.println (A1.show (d)); ③
System.out.println (A2.show (b)); ④
System.out.println (A2.show (c)); ⑤
System.out.println (A2.show (d)); ⑥
System.out.println (B.show (b)); ⑦
System.out.println (B.show (c)); ⑧
System.out.println (B.show (d)); ⑨

(c) The answer

①a and A
②a and A
③a and D
④b and A
⑤b and A
⑥a and D
⑦b and B
⑧b and B
⑨a and D

(iv) Analysis

①②③ better understand, generally not wrong. ④⑤ is a bit confused, why is not the output of "B and B" it?!! Let's review polymorphism first.

Run-time polymorphism is one of the most powerful mechanisms for object-oriented programming code reuse, and dynamic concepts can be said to be "an interface, multiple methods". Java implements Run-time polymorphism based on dynamic method scheduling, which is a mechanism for invoking overloaded methods at run time rather than at compile time.

The overridden overriding and overloaded overloading of methods are different manifestations of Java polymorphism. Overriding overriding is a manifestation of polymorphism between parent classes and subclasses, and overload overloading is an expression of polymorphism in a class. If you define a method in a subclass with the same name and parameters as its parent class, we say that the method is overridden (overriding). When an object of a subclass uses this method, the definition in the subclass is invoked, and the definition in the parent class is "masked". If multiple methods with the same name are defined in a class, either with a different number of parameters or with different parameter types, they are called overloads of the Method (overloading). The overloaded method is to change the type of the return value but also to have a different argument list.

When a superclass object references a variable referencing a subclass object, the type of the referenced object, rather than the type of the reference variable, determines whose member method to invoke, but the invoked method must be defined in the superclass, that is, the method overridden by the quilt class. (But if you force a superclass to subclass, you can invoke a method that is not in the subclass of a new addition that is not a superclass.) )

All right, let's go over here and get to the point! In fact, this involves the precedence of method calls, from highest to lowest precedence: This.show (o), Super.show (O), This.show (Super) O), Super.show ((Super) O). Let's take a look at how it works.

For example, ④,a2.show (b), A2 is a reference variable, type A, then this is A2,b is an instance of B, so it finds show (b obj) method inside Class A, not found, and then to a super (superclass) to find, and a does not have a super class, So go to the third priority This.show ((Super) O), this is still A2, where O is B, (Super) O is (super) B is A, so it's looking for show (a obj) in Class A, and Class A has this method, But since A2 refers to an object of Class B, B overwrites the show (a obj) method of a, so it eventually locks into show (a obj) of Class B, and the output is "B and a".

Another example is ⑧,b.show (c), B is a reference variable, the type B, then this is B,c is an instance of C, so it went to Class B to find Show (C obj) method, not found, and then to B's super Class A inside find, there is no, so also go to the third priority This.show ( (Super) O), this is B,o C, (Super) O is (super) C is B, so it went to B to find show (b obj) method, found, because B refers to a Class B object, so directly locked to Class B's show (b obj), the output is "B and B."

According to the above method, you can get the other results correctly.

The question continues, now let's look at how the analysis process above reflects the meaning of the word blue. It says: When a superclass object refers to a variable referencing a subclass object, the type of the referenced object, rather than the type of the reference variable, determines whose member method to invoke, but the invoked method must be defined in the superclass, that is, the method overridden by the quilt class. Let's take A2.show (b) for a while.

        A2 is a reference variable, a type A, which refers to an object of B, so the meaning of this sentence is B to determine which method is invoked. So you should call B's show (b obj) to output "B and B". But why is it inconsistent with the results of the previous analysis?! The problem is that we do not ignore the second half of the blue font, which specifically indicates that the called method must be defined in the superclass, that is, the quilt cover method. B is the show (b obj) defined in Super Class A? No! That's not to mention being covered. In fact, this statement hides a message: it is still determined according to the precedence of the method invocation. It found show (a obj) in class A, if subclass B does not overwrite the show (a obj) method, it calls show (a obj) of a (because B inherits a, although it is not overridden, but inherits this method from superclass a, in a sense, or by B to determine the method of invocation, only the method is implemented in A; now Subclass B covers Show (a obj), so it eventually locks to show (a obj) for B. That's what that sentence means.

Related Article

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.