Hello ranchers,
In K&B Rules for overriding a method - page 102 last point
"The Overriding method can throw newer or fewer exceptions.
Bottom Line: an Overriding method does'nt have to declare any exceptions that it will never throw, regardless of what the overridden medhod declares."
If this is right, why should you get a compiler error with the following code?
page 104 Exam Watch
class Animal{
public void eat() throws 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();
a.eat(); //compiler error- unreported exception
}
}
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.
Can anyone please explain. For be both look so contradicting.
Thank you