Java中的铸造和动态与静态类型 [英] Casting and dynamic vs static type in Java

查看:308
本文介绍了Java中的铸造和动态与静态类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习静态和动态类型,我大部分都是理解它的,但这种情况仍然让我无法理解。

I'm learning about static vs dynamic types, and I am to the point of understanding it for the most part, but this case still eludes me.

如果类 B 扩展 A ,我有:

A x = new B();

是否允许以下​​操作?:

Is the following allowed?:

B y = x;

还是需要显式投放?:

B y = (B) x;


$ b

谢谢!

Thanks!

推荐答案

显式投射是必需的,将会成功。

因为它不总是成功:声明为 A x 的变量可以引用不是 instanceof B的实例

The reason why it's required is because it doesn't always succeed: a variable declared as A x can refer to instances that aren't instanceof B.

// Type mismatch: cannot convert from Object to String
Object o = "Ha!";
String s = o; // DOESN'T COMPILE

// Compiles fine, cast succeeds at run-time
Object o = "Ha!";
String s = (String) o;

// Compiles fine, throws ClassCastException at run-time
Object o = Boolean.FALSE;
String s = (String) o; 

是否只需要通过声明的类型确定是否需要强制转换的所涉及的变量,通过它们在运行时引用的对象的类型来替换。这是真的,即使引用可以在编译时解决。

Whether or not a cast is required is determined only by the declared types of the variables involved, NOT by the types of the objects that they are referring to at run-time. This is true even if the references can be resolved at compile-time.

final Object o = "Ha!";
String s = o; // STILL doesn't compile!!!

这里,即使 final code> o 将始终引用 instanceof String ,其声明的类型仍然为 Object ,因此需要编译

Here, even though the final variable o will always refer to an instanceof String, its declared type is still Object, and therefore an explicit (String) cast is still required to compile.

这篇关于Java中的铸造和动态与静态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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