继承,方法签名,方法重写和throws子句 [英] Inheritance , method signature , method overriding and throws clause

查看:337
本文介绍了继承,方法签名,方法重写和throws子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类是:

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;
   }
}

注意覆盖 Child 类中的 getX 方法,我从方法定义中删除了 throws 子句。现在它会导致编译器出现异常行为:

Notice while overriding the getX method in the Child class , I have removed the throws clause from the method definition .Now it results in an anomalous behavior by the compiler which is expected :

new Parent().getX() ;

如果没有将其封装在 try-catch 阻止,如预期的那样。

does not compile without enclosing it in a try-catch block , as expected .

new Child().getX() ;

编译而不将其包含在 try-catch 阻止。

compiles without enclosing it in a try-catch block .

但下面的代码行需要try-catch块。

But the below lines of code needs the try-catch block .

Parent p = new Child();
p.getX();

因为这可以预见,即在运行时多态性期间使用父类引用来调用子方法,为什么Java的设计者在重写特定的父类方法时没有强制要求在方法定义中包含throws子句?我的意思是如果父类方法在其定义中有throws子句,那么在覆盖它时,重写方法也应该包括throws子句,不是吗?

As this could be foreseen i.e. using a parent class reference to invoke a child method during run-time polymorphism , why the designers of Java didn't make it mandatory to include the throws clause in the method definition while overriding a particular parent class method ? I mean if a parent class method has throws clause in its definition , then while overriding it the overriding method should also include the throws clause , Ain't it ?

推荐答案

不,这是合适的 - 一个重写的方法可以对它抛出(和返回)的内容有更多的限制,因为这对于在编译时知道的调用者是有用的将使用重写方法,并且不想打扰不会发生的异常等。它必须更具限制性而不是更多许可,所以它不能让人惊讶的呼叫者通过父声明访问它。

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.

通过类型为 Parent的引用使用重写方法永远不会违反它可能抛出 IOException 的合同 - 没有异常不会违反合同。反过来说(如果父没有声明异常,但重写方法确实如此)违反合同。

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.

这篇关于继承,方法签名,方法重写和throws子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆