在 Java 中重写时,父子层次结构对抛出是否重要?
javaobject oriented programmingprogramming更新于 2024/8/26 11:55:00
当您尝试处理由特定方法抛出的异常(已检查)时,您需要使用发生异常的 Exception 类或超类来捕获它。
以同样的方式,在重写超类的方法时,如果它抛出异常 −
子类中的方法应该抛出相同的异常或其子类型。
子类中的方法不应抛出其超类型。
您可以重写它而不抛出任何异常。
当您在(层次)继承中有三个名为 Demo、SuperTest 和 Super 的类时,如果 Demo 和 SuperTest 有一个名为sample()。
示例
class Demo { public void sample() throws ArrayIndexOutOfBoundsException { System.out.println("sample() method of the Demo class"); } } class SuperTest extends Demo { public void sample() throws IndexOutOfBoundsException { System.out.println("sample() method of the SuperTest class"); } } public class Test extends SuperTest { public static void main(String args[]) { Demo obj = new SuperTest(); try { obj.sample(); }catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Exception"); } } }
输出
SuperTest 类的 sample() 方法
如果捕获异常的类不是引发异常的类或异常或超类,则会出现编译时错误。
同样,在重写方法时,抛出的异常应该与被重写方法抛出的异常相同或超类,否则会发生编译时错误。
示例
import java.io.IOException; import java.io.EOFException; class Demo { public void sample() throws IOException { System.out.println("sample() method of the Demo class"); } } class SuperTest extends Demo { public void sample() throws EOFException { System.out.println("sample() method of the SuperTest class"); } } public class Test extends SuperTest { public static void main(String args[]) { Demo obj = new SuperTest(); try { obj.sample(); }catch (EOFException ex){ System.out.println("Exception"); } } }
输出
Test.java:12: error: sample() in SuperTest cannot override sample() in Demo public void sample() throws IOException { ^ overridden method does not throw IOException 1 error D:\>javac Test.java Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown obj.sample(); ^ 1 error