Inheritance , method signature , method overriding and throws clause

前端 未结 4 1151
半阙折子戏
半阙折子戏 2021-02-02 12:56

My Parent class is :

import java.io.IOException;
public class Parent {
        int x = 0;
        public int getX() throws IOException{
        if(x         


        
4条回答
  •  迷失自我
    2021-02-02 13:02

    No, this is appropriate - an overridden method can be more restrictive about what it throws (and returns) because this can be useful for callers who know at compile time that they'll be using the overridden method, and don't want to bother with exceptions which can't happen etc. It has to be more restrictive rather than more permissive though, so that it can't surprise callers who do access it through the parent declaration.

    Using the overridden method via a reference of type Parent is never going to violate the contract of "it might throw IOException" - the absence of an exception doesn't violate the contract. The other way round (if the parent didn't declare the exception, but the overriding method does) would be a contract violation.

提交回复
热议问题