SCJP - override method with exception handling raises a compiler error

前端 未结 2 392
旧巷少年郎
旧巷少年郎 2021-01-25 04:43

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


If a method is overridden but you use a polymorphic (supertype) reference to refer to

2条回答
  •  情深已故
    2021-01-25 05:03

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

    • a Dog, then the call will not throw an exception
    • an Animal, then that call could throw

    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.

提交回复
热议问题