将对象强制转换为未实现的接口 [英] Casting an object to an interface which is not implemented
问题描述
我在学习书中发现以下问题,有些困惑:
I found following question in my study book and a bit confused:
给出以下代码,该选项(如果用于替换/* INSERT CODE
HERE */
)将使类型为Roamable
的引用变量引用该对象.
Phone
类? (选择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
强制转换为Roamable
,并且Phone
不是最终的,因此它认为正在转换的对象(虽然称为Phone
)可能是做实现Roamable
的Phone
的子类,因此不会发出编译时错误或警告.
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是最终类(第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屋!