If we consider the previous code the ref variable clearly invokes the overridden method. But in this code why does it call the super class method and produce an error? Since no exceptions are thrown it is less broader than the super class exception. Why does this produce error? Can someone please clearly explain it to me? I cannot understand how exceptions work in overriding.
The correct approach is quintessential in isolating the problem in such cases. Approach such cases in the following manner:
a) Method overriding comes in to play only at run time i.e.
if your code compiles correctly and then you get different behavior when you run it depending on the type of object on the heap. There is no overriding in play at compile time in the second example you quoted. So, clearly it has got to do something with checked exception handling and NOT method overriding.
b) All other method calls are resolved at compile time
based on the reference type of the object. Compiler checks for checked exceptions to be handled or declared at compile time. It sees that the Animal class eat() method declares a checked exception of type Exception. So, it shall force you to
either handle or declare the same when you call that method. That is a rule for handling checked exceptions in
Java language.
Let me know if you have any further doubts regarding the same.