为什么要在 instanceOf 之后强制转换?

Why cast after an instanceOf?(为什么要在 instanceOf 之后强制转换?)

本文介绍了为什么要在 instanceOf 之后强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中(来自我的课程包),我们希望给 Square 实例 c1 一些其他对象 p1 的引用,但前提是这 2 个是兼容的类型.

In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but only if those 2 are of compatible types.

if (p1 instanceof Square) {c1 = (Square) p1;}

这里我不明白的是,我们首先检查 p1 确实是一个 Square,然后我们仍然对其进行投射.如果是Square,为什么要投?

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it. If it's a Square, why cast?

我怀疑答案在于表面类型和实际类型之间的区别,但我仍然感到困惑......

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...


编译器会如何处理:


How would the compiler deal with:

if (p1 instanceof Square) {c1 = p1;}


instanceof 检查的是 actual 类型而不是 apparent 类型的问题吗?然后演员改变了明显的类型?


Is the issue that instanceof checks for the actual type rather than the apparent type? And then that the cast changes the apparent type?

推荐答案

请记住,您始终可以将 Square 的实例分配给继承链更高的类型.然后,您可能希望将不太具体的类型转换为更具体的类型,在这种情况下,您需要确保您的转换是有效的:

Keep in mind, you could always assign an instance of Square to a type higher up the inheritance chain. You may then want to cast the less specific type to the more specific type, in which case you need to be sure that your cast is valid:

Object p1 = new Square();
Square c1;

if(p1 instanceof Square)
    c1 = (Square) p1;

这篇关于为什么要在 instanceOf 之后强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么要在 instanceOf 之后强制转换?

基础教程推荐