【问题标题】:Overriding a method that has an Exception Compiler Error覆盖具有异常编译器错误的方法
【发布时间】: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()' 中的子类型覆盖?

【问题讨论】:

  • 因为aAnimal
  • 因为一般情况下是看不到的。它必须是一致的。

标签: java inheritance compiler-errors polymorphism subtype


【解决方案1】:

尽管引用“a”的实际对象是 Dog 类型,但变量“a”的类是 Animal 类。

因此在编译时编译器假定 a.eat() 可能会抛出异常,因为 Animal eat() 方法声明了它,因此期望这个调用要么包装在 try catch 中,要么让方法调用者有一个 throw子句。

【讨论】:

    【解决方案2】:

    编译器只知道aAnimal。那是因为拥有是完全合法的

    class HairballException extends Exception {}
    
    class Cat extends Animal {
        public void eat() throws HairballException {}
    }
    

    然后在a.eat();之前:

    a = new Cat();
    

    变量a 可以是Animal任何 类。编译器不能假定a 仍然是Dog,所以它必须强制它可以抛出Exception

    如果您真的不想捕获Animaleat() 方法可能抛出的Exception,那么在调用eat() 之前将a 转换为Dog

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-29
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多