JAVA把对象转成接口,Java将一个对象转换为未实现的接口

I found following question in my study book and a bit confused:

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

}

Options are:

Roamable var = new Phone();

Roamable var = (Roamable)Phone();

Roamable var = (Roamable)new Phone();

Because interface Roamable and class Phone are unrelated, a reference variable

of type Roamable can’t refer to an object of class Phone.

I thought the correct option is 4, however it says it is 3.

But, Phone doesn't implement Roamable interface, so you can't cast, can you?

解决方案

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.

5.5.1. Reference Type Casting

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.

The following code compiles:

interface Roamable{}

class Phone {}

class Tablet extends Phone implements Roamable {

Roamable var = (Roamable)new Phone(); // Compiles

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值