我在我的学习书中发现了以下问题并且有点困惑:
给定以下代码,哪个选项,如果用来替换/* INSERT CODE
HERE */
,将使 Roamable
类型的引用变量能够引用
Phone
类? (选择 1 个选项。)
interface Roamable{}
class Phone {}
class Tablet extends Phone implements Roamable {
//INSERT CODE HERE
}
选项是:
可漫游 var = new Phone();
可漫游 var = (Roamable)Phone();
Roamable var = (Roamable)new Phone();
- 因为接口(interface)
Roamable
和类Phone
不相关,引用变量Roamable
类型的对象不能引用Phone
类的对象。
我认为正确的选项是 4,但它说是 3。
但是,Phone
没有实现Roamable
接口(interface),所以你不能转换,对吗?
最佳答案
正确答案是 3
:编译器只看到 Phone
被转换为 Roamable
和 Phone
不是最终的,所以它认为被转换的对象,尽管被称为 Phone
可能是 Phone
的子类,确实实现 Roamable
,因此不会发出编译时错误或警告。
5.5.1。引用类型转换
Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules. If T is an interface type:
If S is not a final class (§8.1.1), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.
Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).
If S is a final class (§8.1.1), then S must implement T, or a compile-time error occurs.
编译以下代码:
interface Roamable{}
class Phone {}
class Tablet extends Phone implements Roamable {
Roamable var = (Roamable)new Phone(); // Compiles
}
关于java - 将对象转换为未实现的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812289/