RESULT:compilation fails due to line 3
method on line 2 has been overrided ,ok
in overriding ,object type determines which method has to be invoked,so in line3 method in class B should be invoked,which is not throwing exception,i don't think line3 should be in try catch block.
Then why compilation fails?please explain the logic behind this.
Abimaran Kugathasan wrote:At compile time, the compiler checks the reference type, not the actual object! So, a Compilation error!
Abimaran is correct. Since the compiler checks the reference type while compiling, it gives error with a.foo() because it throws Exception and it is not caught any where.
If you look closely, even if you add try catch block around line 3, it will NOT solve the issue. foo() method of Class A is still declared to throw an Exception.
So either you have to add a try/catch inside main() where a.foo() is called or you need to declare
for the code to compile.