关于转换的Java编译问题
如果我有两个彼此不相关的对象。以下情况会发生什么情况: 我们有:对象 A、对象 B
A a = new A();
B b = new B();
- a = b; \会编译吗?我会得到例外吗?
- a = (A) b; \将编译?之后 - 我会得到例外吗?
If I have two objects not related to each other. What will happen in the following cases:
We have: Object A, Object B
A a = new A();
B b = new B();
- a = b; \will compile? will I get an exception?
- a = (A) b; \will compile ? afterwards - will I get an exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者都不会编译,在第二种情况下,只有编译器可以检查类型时,所以如果您首先通过 Object,您将能够在运行时进行强制转换并获得异常
Both won't compile, in the second case only if the compiler can check the types, so if you first go through Object you would be able to cast and get an exception at runtime
如果两个对象不相关,您将无法将其中一个对象转换为另一个对象。
1. 不会编译。
2. 会编译,但会在运行时抛出异常。
如果一个对象是从另一个对象继承的,那么您就可以将一个对象强制转换为另一个对象。
If the two objects are unrelated you will not be able to cast one to the other.
1. Will not compile.
2. Will compile, but will throw an exception at runtime.
If one object was inherited from the other, then you would be able to cast the one to the other.
您也可以简单地编译它们来获得答案。
否不会编译
否不会编译
另请参阅
You can simply compile them to get the answer as well.
No Won't compile
No Won't compile
See Also