'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()'中的子类型覆盖?
答案 0 :(得分:1)
编译器只知道a
是Animal
。那是因为拥有
class HairballException extends Exception {}
class Cat extends Animal {
public void eat() throws HairballException {}
}
然后在a.eat();
之前:
a = new Cat();
变量a
可以是任何类Animal
。编译器不能假设a
仍然是Dog
,因此必须强制它可以抛出Exception
。
如果你真的不想抓住Exception
Animal
方法可能抛出的eat()
,那么请先将a
投射到Dog
致电eat()
。
答案 1 :(得分:0)
即使引用'a'的实际对象是Dog类型,变量'a'的类也是类Animal。
因此在编译时,编译器假定a.eat()可能会抛出异常,因为Animal eat()方法声明它,因此希望此调用包含在try catch中或者方法调用者有一个throw子句。