Hi
I'm reading K & B 1.5
SCJP Certification text. Can you clarify a portion of the text which seems contradictory?
The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. (PAGE 102-103)
If a method is overridden but you can 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). Let's take a look at an example: (PAGE 104)
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. (PAGE 104)
In the example quoted above the overriding method in the Dog2 subclass doesn't declare an exception that it will never throw, even though the overriden eat() method in Animal declares the exception. The Dog2 subclass is taking "greater risks" by not declaring the exception, but the eat() method in the Dog2 subclass will never throw an exception. I may be splitting hairs, but I'm interested in anything which will clarify my understanding. Thanks.