Java 中接口的抽象方法会抛出异常吗?
java 8object oriented programmingprogramming
是的,接口的抽象方法会抛出异常。
示例
在下面的例子中,接口 (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