相关疑难解决方法(0)

ClassCastException与"无法强制转换"编译错误

为我的OCA Java SE 7程序员学习考试,所以新手问题.我有一个我不明白的例子问题.以下代码编译,但在运行时给出ClassCastException:

interface Roamable {
}

class Phone {
}

public class Tablet extends Phone implements Roamable {
    public static void main(String... args) {
        Roamable var = (Roamable) new Phone();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我改变Roamable var = (Roamable) new Phone();Roamable var = (Roamable) new String();我得到一个编译错误的时候了.

两个问题:

  1. 为什么上面的代码完全编译?电话似乎与Roamable无关?
  2. 为什么代码编译new Phone(),但不编译new String()

java inheritance casting classcastexception

14
推荐指数
1
解决办法
4178
查看次数

标签 统计

casting ×1

classcastexception ×1

inheritance ×1

java ×1