【问题标题】:Casting a class to an unrelated interface将类转换为不相关的接口
【发布时间】:2013-10-02 16:11:53
【问题描述】:

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

【问题讨论】:

  • 因为多态性发生在运行时。
  • 但是编译器知道 Cat 没有实现 Furniture,并且在运行时不能改变?我可能遗漏了一个简单的观点,但你的回答并没有真正帮助我
  • 因为。尽管 Cat 可能不会直接实现 Furniture,但 Cat 的某些超类可能会。并且编译器选择不深入研究这些丑陋的细节,因为接口的规则非常复杂。 (谢谢你,Sun。)并且没有一般规则要求编译器检测不可避免的运行时异常(例如除以零)——它更多的是它提供的“服务”。跨度>

标签: java interface casting compilation runtime


【解决方案1】:

编译的原因

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

【讨论】:

  • 注意如果Cat被声明为final,编译器确实会抱怨(它会知道Cat的任何子类都不能实现Furniture,因为不可能有子类Cat)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-31
  • 2020-12-06
相关资源
最近更新 更多