将对象转换为未实现的接口 [英] Casting an object to an interface which is not implemented
问题描述
我在我的学习书中发现了以下问题,有点困惑:
I found following question in my study book and a bit confused:
给定下面的代码,哪个选项,如果用来替换/* INSERT CODEHERE */
,将启用 Roamable
类型的引用变量来引用电话
类?(选择 1 个选项.)
Given the following code, which option, if used to replace /* INSERT CODE
HERE */
, will enable a reference variable of type Roamable
to refer to an object of the
Phone
class? (Select 1 option.)
interface Roamable{}
class Phone {}
class Tablet extends Phone implements Roamable {
//INSERT CODE HERE
}
选项是:
Roamable var = new Phone();
Roamable var = (Roamable)Phone();
Roamable var = (Roamable)new Phone();
- 因为接口
Roamable
和类Phone
无关,所以引用变量Roamable
类型的对象不能引用Phone
类的对象.
Roamable var = new Phone();
Roamable var = (Roamable)Phone();
Roamable var = (Roamable)new Phone();
- Because interface
Roamable
and classPhone
are unrelated, a reference variable of typeRoamable
can’t refer to an object of classPhone
.
我认为正确的选项是 4,但它说是 3.
I thought the correct option is 4, however it says it is 3.
但是,Phone
没有实现 Roamable
接口,所以你不能投射,对吗?
But, Phone
doesn't implement Roamable
interface, so you can't cast, can you?
推荐答案
正确答案是 3
:编译器只看到 Phone
被强制转换为 3
code>Roamable 并且 Phone
不是最终的,所以它认为被转换的对象,虽然被称为 Phone
可能是 的子类电话
确实实现了Roamable
,因此不会发出编译时错误或警告.
The correct answer is 3
: The compiler sees only that a Phone
is being cast to a Roamable
and that Phone
is not final, so it thinks that the object being cast, although referred to as Phone
may be a subclass of Phone
that does implement Roamable
, so no compile-time error or warning is issued.
根据 JLS 第 5 章
5.5.1.引用类型转换
给定一个编译时引用类型 S(源)和一个编译时引用类型 T(目标),如果由于以下规则没有发生编译时错误,则存在从 S 到 T 的强制转换.如果 T 是接口类型:
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:
如果 S 不是最终类(第 8.1.1 节),那么,如果存在 T 的超类型 X 和 S 的超类型 Y,使得 X 和 Y 都是可证明不同的参数化类型,并且X 和 Y 的擦除相同,则发生编译时错误.
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.
否则,转换在编译时总是合法的(因为即使 S 没有实现 T,S 的子类也可能).
Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).
如果 S 是 final 类(第 8.1.1 节),则 S 必须实现 T,否则会发生编译时错误.
If S is a final class (§8.1.1), then S must implement T, or a compile-time error occurs.
<小时>
以下代码编译:
The following code compiles:
interface Roamable{}
class Phone {}
class Tablet extends Phone implements Roamable {
Roamable var = (Roamable)new Phone(); // Compiles
}
这篇关于将对象转换为未实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!