java - 将对象转换为未实现的接口(interface)

标签 java interface casting

我在我的学习书中发现了以下问题并且有点困惑:

给定以下代码,哪个选项,如果用来替换/* INSERT CODE HERE */,将使 Roamable 类型的引用变量能够引用 Phone 类? (选择 1 个选项。)

interface Roamable{}
class Phone {}
class Tablet extends Phone implements Roamable {
    //INSERT CODE HERE
}

选项是:

  1. 可漫游 var = new Phone();
  2. 可漫游 var = (Roamable)Phone();
  3. Roamable var = (Roamable)new Phone();
  4. 因为接口(interface)Roamable和类Phone不相关,引用变量 Roamable 类型的对象不能引用 Phone 类的对象。

我认为正确的选项是 4,但它说是 3。

但是,Phone 没有实现Roamable 接口(interface),所以你不能转换,对吗?

最佳答案

正确答案是 3:编译器只看到 Phone 被转换为 RoamablePhone 不是最终的,所以它认为被转换的对象,尽管被称为 Phone 可能是 Phone 的子类,确实实现 Roamable,因此不会发出编译时错误或警告。

根据 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 - 将对象转换为未实现的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812289/

相关文章:

Java 从 LocalDateTime Bar 中减去 LocalDateTime foo

c# - 使用 BitConverter 在 C# 中进行快速转换,它能更快吗?

java - MyBatis 获取最后插入的 Id

类层次结构中的 Java 可选接口(interface)

java - 我可以删除 Java 6 而 Android 仍然可以工作吗?

Java服务方法仅用于测试

c# - 无法声明接口(interface) "async Task<myObject> MyMethod(Object myObj); "

Swift double 到字符串

java - 使用与 xml 适配器一起使用的自定义类型编码空值

java - getClass().getResource() 指向什么?