为什么在一个instanceOf之后施放? [英] Why cast after an instanceOf?

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

问题描述

在下面的例子中(来自我的coursepack),我们想要给 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;}

Edit2:

问题是 instanceof 检查实际类型而不是明显的类型?那么演员会改变明显的类型?


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

谢谢,

JDelage

推荐答案

请记住,您总是可以将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之后施放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆