“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
。那是因为拥有它是完全合法的
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()
之前.
关于java - 重写有异常编译器错误的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47783132/