I am trying to relate the example from Chapter5 of K&B with one of the examwatches in Chapter2 (Page 104-Examwatch & Page Page390- Q3). But I have difficulty fixing the unreported exception error while compiling. Can anybody please explain.
Two topics involved here are
1. Overridding a method (I think I understood this right)
Overridding a method of the parent class which declares a checked exception with a method in the subclass that may or may not declare the exception. But if the overridden method declares an exception, it can be a run-time exception or an exception that is not broader than the parent class method.
2. Polymorphic super type reference referring to the subclass type (I still can't understand why the compiler cannot recognize this as the parent class method at compile time. Can somebody please explain this also)
dude at compile time the compiler only knows about the reference variable and that is of Master type....and it can only assume that you are going to call the master method....it is only at the runtime that the jvm knows about the object and accordingly calls the appropriate method
but here at the compile time...you have declared that your master method throws an exception...since your method is throwing a checked exception....you have to put a try catch block around the line which calls the method...
Joined: Sep 06, 2009
this compiles because now the compiler doesnt have a problem since you are catching the error....or what you can do is declare that main method throws filenotfoundexception which is called ducking the exception
Ankur kothari wrote:this compiles because now the compiler doesnt have a problem since you are catching the error....or what you can do is declare that main method throws filenotfoundexception which is called ducking the exception
yes ankur is correct, it is because object create at run time not compile time...at the time of compilation, the compiler think this the method of Master class and it should be catch or throws the exception.