繁体   English   中英

将类转换为不相关的接口

[英]Casting a class to an unrelated interface

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

编译的原因

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM