我的Parent
课是:
import java.io.IOException;
public class Parent {
int x = 0;
public int getX() throws IOException{
if(x<=0){
throw new IOException();
}
return x;
}
}
我extend
这个类写了一个子类Child
:
public class Child1 extends Parent{
public int getX(){
return x+10;
}
}
请注意,在覆盖类中的getX方法时Child
,我已从throws
方法定义中删除了该子句。现在它会导致编译器出现异常行为,这是预期的:
new Parent().getX() ;
try-catch
如预期的那样,如果不将其包含在块中,则不会编译。
new Child().getX() ;
编译时不将其封闭在一个try-catch
块中。
但是下面的代码行需要 try-catch 块。
Parent p = new Child();
p.getX();
正如可以预见的那样,即在运行时多态性期间使用父类引用来调用子方法,为什么 Java 的设计者在重写特定父类方法时没有强制在方法定义中包含 throws 子句?我的意思是,如果父类方法的定义中有 throws 子句,那么在覆盖它时,覆盖方法也应该包括 throws 子句,不是吗?