Downward transformation of Java polymorphism

Downward transformation of Java polymorphism

Upward transformation can be completed automatically, while downward transformation requires forced type conversion.

Cast type

We mentioned the cast of basic data types earlier. You can see the previous article: the cast of basic data types and reference variables is similar to the cast of basic data types, which requires the type conversion operator: ().

//将变量强制转换为type类型
type p = (type)变量

Special attention:

//错误!
boolean boo = true;
int in = (int)boo;
//假设Person类和Dog类不具有继承关系,则下面会出错
Person p = new Person();
Dog dog = (Dog)p;
//假设Student继承于Person类
//编译时正常,运行时出错
Person p = new Person();
Student s = (Student)p;

instanceof

When a parent class reference is assigned to a subclass variable, it must be cast. If there is a mismatch between the two sides of forced type conversion, the runtime passes (RTTI run time type identification), that is, runtime type identification, checks and returns ClassCastException, that is, type conversion exception.

In order to avoid this embarrassing problem, we can use the instanceof operator to check to ensure the robustness of the program. Instance means instance. It can be imagined that instanceof means to judge whether the previous object is an instance of the following class or subclass. If yes, it returns true; otherwise, it returns false.

[引用类型变量] instanceof [类(接口)]

Take any of the above error examples:

//在强制类型转换前加上instanceof语句判断
Person p = new Person();
if (p instanceof Student) {
Student s = ((Student) p);
}

At this time, the if judgment statement is false, which naturally cannot be executed, so as to avoid program error reporting and ensure the robustness of the program.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>