Java介面中的抽象方法可以丟擲異常嗎?


是的,介面的抽象方法可以丟擲異常。

示例

在下面的示例中,介面 (MyInterface) 包含一個名為 *display* 的抽象方法,該方法丟擲 IOException 異常。

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws IOException ;
}

遵循的規則

實現此類方法時,需要遵循以下規則:

  • 如果介面中的抽象方法丟擲某種異常,則實現方法可以丟擲與之相同的異常,如下所示:

示例1

 線上演示

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws IOException ;
}
public class InterfaceExample implements MyInterface{
   public void display()throws IOException {
      System.out.println("This is the subclass implementation of the display method");
   }
   public static void main (String args[]){
      try {
         new InterfaceExample().display();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

This is the subclass implementation of the display method
  • 如果介面中的抽象方法丟擲某種異常,則實現方法可以選擇不丟擲任何異常,如下所示:

示例2

 線上演示

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws IOException ;
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the subclass implementation of the display method");
   }
   public static void main (String args[]){
      try {
         new InterfaceExample().display();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

This is the subclass implementation of the display method
  • 如果介面中的抽象方法丟擲某種異常,則實現方法可以丟擲其子型別:

示例3

 線上演示

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws Exception ;
}
public class InterfaceExample implements MyInterface{
   public void display()throws IOException {
      System.out.println("This is the subclass implementation of the display method");
   }
   public static void main (String args[]){
      try {
         new InterfaceExample().display();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

This is the subclass implementation of the display method
  • 如果介面中的抽象方法丟擲某種異常,則實現方法不應丟擲其超型別

示例4

 線上演示

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws IOException ;
}
public class InterfaceExample implements MyInterface{
   public void display()throws Exception {
      System.out.println("This is the subclass implementation of the display method");
   }
   public static void main (String args[]){
      try {
         new InterfaceExample().display();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

編譯時錯誤

輸出

InterfaceExample.java:8: error: display() in InterfaceExample cannot implement display() in MyInterface
   public void display()throws Exception {
               ^
   overridden method does not throw Exception
1 error

更新於:2020年6月29日

2K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.