首页 > 解决方案 > 为什么超类方法可以在超类方法中声明不异常?

问题描述

我正在阅读 Kathey sierra 的 SCJP 6 书,并遇到了在覆盖方法中抛出异常的解释。我完全没听懂。谁能向我解释为什么我们不能使用 Dog2 对象在 Animal 引用上调用 eat() 方法?

class Animal {
    public void eat() throws Exception {
        // throws an Exception
    }
}
class Dog2 extends Animal {
    public void eat() { /* no Exceptions */}
    public static void main(String [] args) {
        Animal a = new Dog2();
        Dog2 d = new Dog2();
        d.eat(); // ok
        a.eat(); // compiler error - unreported exception
    }
}

这个问题可能是重复的,但该问题也没有给出答案。有人可以解释编译器的行为吗?

标签: javaoverriding

解决方案


推荐阅读