Why cast after an 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 之后强制转换?
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01