Java 中的转换和动态与静态类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2672645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:18:17  来源:igfitidea点击:

Casting and dynamic vs static type in Java

javacasting

提问by XpdX

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.

我正在学习静态与动态类型,并且我在很大程度上理解了它,但这种情况仍然让我难以理解。

If class Bextends A, and I have:

如果 class Bextends A,我有:

A x = new B();

Is the following allowed?:

是否允许以下​​内容?:

B y = x;

Or is explicit casting required?:

还是需要显式转换?:

B y = (B) x;

Thanks!

谢谢!

回答by polygenelubricants

Explicit casting is required, and will succeed.

显式转换是必需的,并且会成功

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

之所以需要它,是因为它并不总是成功:声明为 as 的变量A x可以引用不是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 onlyby the declared types of the variables involved, NOTby 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!!!

Here, even though the finalvariable owill always refer to an instanceof String, its declared type is still Object, and therefore an explicit (String)cast is stillrequired to compile.

在这里,即使final变量o总是指的是instanceof String,它的声明类型仍然是Object的,因此一个明确的(String)强制转换仍然需要进行编译。