Home  >  Article  >  Java  >  JAVA polymorphism introduced from shallow to deep

JAVA polymorphism introduced from shallow to deep

高洛峰
高洛峰Original
2017-01-21 16:59:421146browse

What is polymorphism?

Polymorphism is divided into two types:

(1) Compile-time polymorphism (design-time polymorphism): method overloading.

(2) Runtime polymorphism: The JAVA runtime system determines which method to call based on the type of instance that calls the method, which is called runtime polymorphism. (We usually talk a lot about runtime polymorphism, so polymorphism mainly refers to runtime polymorphism)

Three necessary conditions for the existence of runtime polymorphism:
1. There must be inheritance ( Including the implementation of the interface);
2. Rewriting is required;
3. The parent class reference points to the subclass object.

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

Detailed explanation:

Explanation of runtime polymorphism: a. Runtime polymorphism refers to the specific type pointed to by the reference variable defined in the program and b. The method call issued through the reference variable is not determined when programming, but when the program is running It is determined during this period that a reference variable will point to an instance object of which class. The method call issued by the reference variable is a method implemented in which class. This must be determined during the running of the program.

1 .The specific type pointed to by the reference variable defined in the program is uncertain (that is, which class instance object a reference variable will point to).

Example:

drive method in driver class (Vehicle class vehicle) {}

•oneDriver.drive( new car() )
•oneDriver.drive( new bus() )
The vehicle variable cannot determine which subclass instance is used.

1. The method call issued through the reference variable is not determined during programming (the method call issued by the reference variable is a method implemented in which class).

Example: The Cut method of the chef, gardener, and barber calls .persion.cut().

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

Benefits of polymorphism:

1. Substitutability. Polymorphism enables replacement of existing code. For example, polymorphism works for the Circle class, but it also works for any other circular geometry, such as a torus.

2. Extensibility. Polymorphism makes code extensible. Adding new subclasses does not affect the polymorphism, inheritance, and operation and operation of other features of existing classes. In fact, it is easier to add new subclasses to obtain polymorphic functions. For example, after realizing the polymorphism of cones, semi-cones and hemispheres, it is easy to add the polymorphism of sphere class.

3. Interface-ability. Polymorphism is achieved by the superclass providing a common interface to subclasses through method signatures, and the subclasses completing or overriding it. As shown in Figure 8.3. The super class Shape in the figure specifies two interface methods that implement polymorphism, computeArea() and computeVolume(). Subclasses, such as Circle and Sphere, improve or override these two interface methods in order to achieve polymorphism.

4. Flexibility. It embodies flexible and diverse operations in applications and improves usage efficiency.

5. Simplicity. Polymorphism simplifies the code writing and modification process of application software. This feature is particularly prominent and important when dealing with calculations and operations on a large number of objects.

Practical application:

Combined with the use of configuration files, contact the Spring framework, use reflection, and dynamically call classes without modifying the source code. Directly add new classes and modify configuration files. No need The program can be expanded by restarting the server.

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

Summary:

Use a reference of the parent class type to point to the object of the subclass. The reference calls the methods and variables defined in the master class. The variables cannot be overridden (overwritten); if a method in the parent class is overridden in the subclass, then in When this method is called, the method in the subclass will be called;

Pay attention to special circumstances. If the parameter list of the method called by the parent class reference is undefined, the parent class of the parent class will be called to find it. , if it is not found yet, force up-type conversion to the parameter type in the parameter list. The specific priority from high to low is as follows:

this.show(O), super.show(O), this.show( (super)O), super.show((super)O).

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

Classic written test questions (mixed overloading and Rewritten):

(1) Related classes

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...{}

(2) Question: What is the following output result?

        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));   ②
        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));     ⑨   

(三)答案

              ①   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

(四)分析

        ①②③比较好理解,一般不会出错。④⑤就有点糊涂了,为什么输出的不是"B and B”呢?!!先来回顾一下多态性。

        运行时多态性是面向对象程序设计代码重用的一个最强大机制,动态性的概念也可以被说成“一个接口,多个方法”。Java实现运行时多态性的基础是动态方法调度,它是一种在运行时而不是在编译期调用重载方法的机制。

        方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写(Overriding)。子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义如同被“屏蔽”了。如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(Overloading)。Overloaded的方法是可以改变返回值的类型但同时参数列表也得不同。

        当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。 (但是如果强制把超类转换成子类的话,就可以调用子类中新添加而超类没有的方法了。)

        好了,先温习到这里,言归正传!实际上这里涉及方法调用的优先问题 ,优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。让我们来看看它是怎么工作的。

        比如④,a2.show(b),a2是一个引用变量,类型为A,则this为a2,b是B的一个实例,于是它到类A里面找show(B obj)方法,没有找到,于是到A的super(超类)找,而A没有超类,因此转到第三优先级this.show((super)O),this仍然是a2,这里O为B,(super)O即(super)B即A,因此它到类A里面找show(A obj)的方法,类A有这个方法,但是由于a2引用的是类B的一个对象,B覆盖了A的show(A obj)方法,因此最终锁定到类B的show(A obj),输出为"B and A”。

        Another example is ⑧, b.show(c), b is a reference variable with type B, then this is b, and c is an instance of C, so it goes to class B to find the show(C obj) method, but there is no Found it, then go to B's super class A to find it. There is no such thing in A, so we also go to the third priority level this.show((super)O). This is b, O is C, (super)O is ( super)C is B, so it looks for the show(B obj) method in B and finds it. Since b refers to an object of class B, it is directly locked to the show(B obj) of class B, and the output is "B and B”.

By following the above method, you can get other results correctly.

The question continues. Now let’s look at how the above analysis process reflects the connotation of the sentence in blue font. It says: 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 whose member method is called, but the called method must be defined in the superclass. In other words, methods that are overridden by subclasses. Let’s take a2.show(b) as an example.

A2 is a reference variable, the type is A, which quotes a object of B, so this sentence means which method is determined by B to determine the call. Therefore, B's show(B obj) should be called to output "B and B". But why is it inconsistent with the results obtained from the previous analysis? ! The problem is that we should not ignore the second half of the blue font, which specifically states: The called method must be defined in the super class, that is, a method overridden by the subclass. Is show(B obj) in B defined in superclass A? No! That's not to mention being covered. In fact, this sentence hides a message: it is still determined according to the priority of method calls. It finds show(A obj) in class A. If subclass B does not override the show(A obj) method, then it calls A's show(A obj) (since B inherits A, although this method is not overridden, This method is inherited from superclass A. In a sense, B still determines the method to be called, but the method is implemented in A); now subclass B overrides show(A obj), so it finally Lock to B's show(A obj). That's what that statement means.

For more JAVA polymorphism, please pay attention to the PHP Chinese website for related articles introduced from shallow to deep!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn