【发布时间】:2017-12-12 23:18:30
【问题描述】:
“a.eat()”下面的代码会导致需要声明或捕获的编译错误。
class Animal {
public void eat() throws Exception {}
}
class Dog extends Animal {
public void eat() {}
public static void main(String [] args) {
Animal a = new Dog();
Dog d = new Dog();
d.eat();
a.eat();//Causes compilation error as 'a' was not declared or caught
}
}
为什么编译器仍然认为您正在调用声明异常的方法?为什么编译器没有看到该方法已被 'd.eat()' 中的子类型覆盖?
【问题讨论】:
-
因为
a是Animal。 -
因为一般情况下是看不到的。它必须是一致的。
标签: java inheritance compiler-errors polymorphism subtype