加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 06:03:59 所属栏目:Java 来源:网络整理
导读:我在学习书中发现了以下问题,有点困惑: 给出以下代码,哪个选项,如果用于替换/ * INSERT CODE HERE * /,将启用Roamable类型的引用变量来引用该对象 电话课? (选择1个选项.) interface Roamable{}class Phone {}class Tablet extends Phone implements Roama
我在学习书中发现了以下问题,有点困惑:

给出以下代码,哪个选项,如果用于替换/ * 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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读