Removing throws in overriden method, compiler wants a try/catch block when invoking

后端 未结 3 1552
轻奢々
轻奢々 2021-01-20 14:38

I have a subclass and I am overriding the inherited parent method: I am removing the throws clause from the method declaration.

Now, using polymorphism, the my insta

3条回答
  •  萌比男神i
    2021-01-20 14:57

    Compiler is right. The line

    A a = new SubB();

    "Means "create instance of class SubB and assign it to variable of type A".

    This means that from this point the variable a's type is A, not SubB. But foo() defined in A throws unchecked Exception that must be re-thrown or caught by caller. This is what compiler tells you.

    At line a.foo() compiler already "does not know" that the real instance type is SubB. It treats it as A.

提交回复
热议问题