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