SCJP - 具有异常处理的覆盖方法会引发编译器错误 [英] SCJP - override method with exception handling raises a compiler error

查看:100
本文介绍了SCJP - 具有异常处理的覆盖方法会引发编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kathey Sierra的SCJP书中,摘录如下:

In the SCJP book by Kathey Sierra, an excerpt is as follows:


如果一个方法被覆盖但你使用多态(超类型)
引用来引用带有重写方法的子类型对象,
编译器假定你正在调用
方法的超类型版本。如果超类型版本声明了一个已检查的异常,但是
重写子类型方法没有,则编译器仍然认为你是
调用一个声明异常的方法(在第5章中有更多内容)。

If a method is overridden but you use a polymorphic (supertype) reference to refer to the subtype object with the overriding method, the compiler assumes you’re calling the supertype version of the method. If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception (more in Chapter 5).

让我们来看一个例子:

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
    }
}

由于在Animal
eat()方法上声明的异常,此代码将无法编译。即使在运行时使用的eat()
方法是Dog版本,也不会声明
异常。

This code will not compile because of the Exception declared on the Animal eat() method. This happens even though, at runtime, the eat() method used would be the Dog version, which does not declare the exception.






现在我不明白的是怎么来 a.eat(); 加注编译错误?
(子项中的重写函数即使在Super时也可能没有任何异常)


Now what I don't understand is that how come a.eat(); raises a compiler error? (overridden function in child may not have any Exception even when Super does)

推荐答案

当你查看代码时,你可以意识到:当你调用eat()on的对象是

When you look at the code, you can realize: when the object you invoke eat() on is


  • 一只狗,那么这个调用不会抛出异常

  • 一个动物,然后该召唤可以抛出

因此,第二次使用导致编译器抱怨你。

Because of that, the second usage results in the compiler complaining to you.

覆盖方法并减少投掷签名完全没问题。当子类永不抛出时,知道如何处理异常的调用者确实有效。

Overriding a method and to reduce the throws signature is perfectly fine. A caller that knows how to deal with an exception for sure works when a sub class never throws.

这篇关于SCJP - 具有异常处理的覆盖方法会引发编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆