Ben Zaidi wrote:Hi,
In K&B book page 104, chapter, an example in exam watch is givenclass 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
}
}
I have a query, why the compiler is looking at the Dog verison of eat method. Though at compile time,
compiler sees the reference type rather then actual object type. Then why it is saying unhandled exception,
though it must see the animal version of the eat method, which is handling the exception
Though at compile time, compiler sees the reference type rather then actual object type. - YES, INDEED! You are absolutely right. Polymorphysm works during the runtime.
Then why it is saying unhandled exception,
though it must see the animal version of the eat method, which is handling the exception - NO. You don't handle this exception. You only report it - "throws" keyword. Handling an exception means:
1). try{}catch(){}
2). Or to pass the exception higher.
1).try{
a.eat();
}catch(Exception ex){ ex.printStackTrace();}
2).
public static void main(String [] args) throws Exception
That should work. Am I right?