Home > Java > Javagetting Started > body text

java object-oriented - detailed introduction to polymorphism

王林
Release: 2019-11-30 14:21:33
forward
2980 people have browsed it

java object-oriented - detailed introduction to polymorphism

1. Overview

Polymorphism is the third major feature of object-oriented after encapsulation and inheritance.

In life, for example, running movements, kittens, puppies and elephants run differently. Another example is the movement of flying. Insects, birds and airplanes also fly differently. It can be seen that the same behavior can be manifested in different forms through different things. Polymorphism describes this state.

Polymorphism:

refers to the same behavior with multiple different manifestations.

Prerequisite [Key points]

1. Inherit or implement [Choose one of two]

2. Rewrite the method [Meaning: Not important Write, meaningless]

3. The parent class reference points to the subclass object [Format reflection]

Free online learning video recommendation: java video

2. Polymorphic manifestation

Format of polymorphic manifestation:

父类类型 变量名 = new 子类对象; 
变量名.方法名();
Copy after login

Parent class type: refers to the parent class type inherited by the subclass object, or implemented The parent interface type.

The code is as follows:

Fu f = new Zi(); 
f.method();
Copy after login

When calling a method using polymorphism, first check whether the method exists in the parent class. If not, A compilation error occurs; if so, the overridden method of the subclass is executed.

The code is as follows:

Define the parent class:

java object-oriented - detailed introduction to polymorphism

Define the subclass:

java object-oriented - detailed introduction to polymorphism

Define test class:

java object-oriented - detailed introduction to polymorphism

3. The benefits of polymorphism

The actual development process In the method, the parent class type is used as a method formal parameter to pass the subclass object to the method and call the method, which can better reflect the scalability and convenience of polymorphism.

The code is as follows:

Define the parent class:

java object-oriented - detailed introduction to polymorphism

Define the subclass:

java object-oriented - detailed introduction to polymorphism

Define test class:

public class Test {
    public static void main(String[] args) {
        // 多态形式,创建对象
        // Cat c = new Cat();
        // Dog d = new Dog();

        // 调用showCatEat showCatEat(c);
        // 调用showDogEat
        showDogEat(d);

        /*
        以上两个方法, 均可以被showAnimalEat(Animal a)方法所替代而执行效果一致
        */
        showAnimalEat(c);
        showAnimalEat(d);
    }

    public static void showCatEat(Cat c) {
        c.eat();
    }

    public static void showDogEat(Dog d) {
        d.eat();
    }

    public static void showAnimalEat(Animal a) {
        a.eat();
    }
}
Copy after login

When the eat method is executed, polymorphism stipulates that the method rewritten by the subclass is executed, so the effect is naturally consistent with the showCatEat and showDogEat methods, so showAnimalEat can completely replace the above two method.

Not only replacement, in terms of scalability, no matter how many subclasses appear in the future, we do not need to write the showXxxEat method, we can directly use showAnimalEat to complete it.

So, the benefit of polymorphism is that it can make the program writing easier and have good expansion.

4. Reference type conversion

Polymorphic transformation is divided into two types: upward transformation and downward transformation:

Upcasting

Upcasting: Polymorphism itself is the process of upconverting subclass types to parent class types. This process is the default.

When the parent class reference points to a subclass object, it is an upward transformation.

Usage format:

父类类型 变量名 = new 子类类型(); 
如:Animal a = new Cat();
Copy after login

Downcasting

The process of downconverting parent class type to subclass type, this process is mandatory.

For a subclass object that has been upwardly transformed, to convert the parent class reference into a subclass reference, you can use the format of forced type conversion, which is downward transformation.

Usage format:

子类类型 变量名 = (子类类型) 父类变量名; 
如 :Cat c =(Cat) a;
Copy after login

Transformation demonstration, the code is as follows:

Define class:

java object-oriented - detailed introduction to polymorphism

Define test class:

java object-oriented - detailed introduction to polymorphism

Transformation exception

转型的过程中,一不小心就会遇到这样的问题,请看如下代码:

java object-oriented - detailed introduction to polymorphism

这段代码可以通过编译,但是运行时,却报出了ClassCastException,类型转换异常!这是因为,明明创建了Cat类型对象,运行时,当然不能转换成Dog对象的。这两个类型并没有任何继承关系,不符合类型转换的定义。

为了避免ClassCastException的发生,Java提供了 关键字,给引用变量做类型的校验。

格式如下:

变量名 instanceof 数据类型
如果变量属于该数据类型,返回true。
如果变量不属于该数据类型,返回false。
Copy after login

所以,转换前,我们最好先做一个判断,代码如下:

java object-oriented - detailed introduction to polymorphism

想学习更多相关教程请访问:java入门学习

The above is the detailed content of java object-oriented - detailed introduction to polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!