覆盖具有异常编译器错误的方法

时间:2017-12-12 23:18:30

标签: java inheritance compiler-errors polymorphism subtype

'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()'中的子类型覆盖?

2 个答案:

答案 0 :(得分:1)

编译器只知道aAnimal。那是因为拥有

是完全合法的
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子句。