Inheritance , method signature , method overriding and throws clause

前端 未结 4 1153
半阙折子戏
半阙折子戏 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:03

    Well, the overriding method might not throw any exception at all (or at least fewer exceptions), thus you can remove exceptions from the throw clause (or the throw clause as a whole).

    Suppose the overriding method catches all exceptions, logs them and returns a special value. Although that's not good style (it would change the semantics of the method) it is still possible andd thus you'd not have to catch exceptions that are never thrown if you know at compile time that you're dealing with a Child.

    Adding exceptions won't work, since users of the class who access it through the Parent reference don't know of any exceptions that Child might add.

提交回复
热议问题