简体   繁体   English

有关强制转换的Java编译问题

[英]Java compilation question regarding casting

If I have two objects not related to each other. 如果我有两个彼此不相关的对象。 What will happen in the following cases: We have: Object A, Object B 在以下情况下会发生什么:我们有:对象A,对象B

A a = new A();
B b = new B();
  1. a = b; a = b; \\will compile? \\会编译吗? will I get an exception? 我会例外吗?
  2. a = (A) b; a =(A)b; \\will compile ? \\会编译吗? afterwards - will I get an exception? 之后-我会例外吗?

You can simply compile them to get the answer as well. 您可以简单地编译它们以获取答案。

  1. No Won't compile ,不会编译

  2. No Won't compile ,不会编译

See Also 也可以看看

两者都不会编译,在第二种情况下,只有在编译器可以检查类型的情况下,因此,如果您首先通过Object,您将能够在运行时进行强制转换并获取异常

If the two objects are unrelated you will not be able to cast one to the other. 如果两个对象不相关,则您将无法将一个对象转换为另一个对象。 1. Will not compile. 1.不会编译。 2. Will compile, but will throw an exception at runtime. 2.将编译,但在运行时将引发异常。

If one object was inherited from the other, then you would be able to cast the one to the other. 如果一个对象是从另一个对象继承的,则可以将一个对象转换为另一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM