给出以下代码,哪个选项,如果用于替换/ * INSERT CODE
HERE * /,将启用Roamable类型的引用变量来引用该对象
电话课? (选择1个选项.)
interface Roamable{} class Phone {} class Tablet extends Phone implements Roamable { //INSERT CODE HERE }
选项包括:
> Roamable var = new Phone();
> Roamable var =(Roamable)电话();
> Roamable var =(Roamable)新手机();
>因为界面Roamable和类Phone不相关,所以是引用变量
Roamable类型不能引用Phone类的对象.
我认为正确的选项是4,但它说它是3.
但是,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 }