11

显然,这会导致编译错误,因为 Chair 与 Cat 无关:

class Chair {}
class Cat {}

class Test {
   public static void main(String[] args) {
       Chair chair = new Char(); Cat cat = new Cat();
       chair = (Chair)cat; //compile error
   }
}

那么为什么我只在运行时将 Cat 引用投射到不相关的接口 Furniture 时才得到异常,而编译器可以明显看出 Cat 没有实现 Furniture?

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}
4

1 回答 1

16

编译的原因

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}

是你很可能有

public class CatFurniture extends Cat implements Furniture {}

如果您创建一个CatFurniture实例,您可以将其分配给Cat cat并且该实例可以强制转换为Furniture. 换句话说,某些Cat子类型可能确实实现了该Furniture接口。

在你的第一个例子中

class Test {
    public static void main(String[] args) {
        Chair chair = new Char(); Cat cat = new Cat();
        chair = (Chair)cat; //compile error
    }
}

某些子类型不可能Cat扩展Chair,除非Cat它本身从Chair.

于 2013-10-02T16:47:49.100 回答