在 Java 中重寫方法時,父類子類繼承關係對丟擲異常重要嗎?
當您嘗試處理特定方法丟擲的異常(已檢查)時,您需要使用**Exception**類或發生異常的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");
}
}
}輸出
sample() method of the SuperTest class
如果捕獲異常的類與丟擲的異常或異常的超類不相同,則會收到編譯時錯誤。
同樣,在重寫方法時,丟擲的異常應與被重寫方法丟擲的異常相同或為其超類,否則會發生編譯時錯誤。
示例
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP