Removing throws in overriden mode, the compiler wants a try / catch block when called

I have a subclass and I override the inherited parent method: I remove the throws clause from the method declaration.

Now, using polymorphism, the execution type of the instance of my instance should determine the implementation of the method; however, the compiler complains and wants to block try / catch around the method call when trying to compile, as if the superclass method was called, and not the version of the subclass?

I know that I can remove the throws declaration or narrow down the thrown exception that can be thrown when overriding. Why is this still throwing an exception?

class A{
    void foo()throws Exception{throw new Exception();}
}    

class SubB extends A{
    @Override
    void foo(){  System.out.println("B");  
}

public static void main(String[] args) {
    A a = new SubB();
    a.foo(); //compiler reports: unhandled exception type Exception 
}
+3
source share
3 answers

ses a A, . , , , SubB,

SubB b = new SubB();
b.foo();
+7

, SubB a , SubB. a, a.foo() ( JLS) Exception.

, () , .

+1

.

A a = new SubB();

"" SubB A ".

This means that from this point the variable type Ais equal to A, but not SubB. But foo(), defined in A, throws an unchecked exception that must be re-fetched or caught by the caller. This is indicated by the compiler.

On the line, the a.foo() compiler no longer “knows” what the type of the real instance is SubB. He sees it as A.

+1
source

All Articles