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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP