Java:将类转换为不相关的接口

时间:2013-10-02 16:11:54

标签: java interface casting compilation runtime

显然,这会导致编译错误,因为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
   }
}

1 个答案:

答案 0 :(得分:12)

编译的原因

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