Java将对象转换为未实现的接口

前端之家收集整理的这篇文章主要介绍了Java将对象转换为未实现的接口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在学习书中发现了以下问题,有点困惑:

给出以下代码,哪个选项,如果用于替换/ * 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界面,所以你不能施展,可以吗?

解决方法

正确的答案是3:编译器只看到一个Phone被强制转换为Roamable并且该Phone不是final,因此它认为正在转换的对象虽然被称为Phone,但它可能是实现Roamable的Phone的子类,因此不会发出编译时错误或警告.

根据JLS chapter 5

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相关文章