如何在 Java 中只覆蓋介面的幾個方法?


從具體類實現介面後,你需要為其所有方法提供實現。如果你在編譯時嘗試跳過實現介面的方法,則會產生一個錯誤。

示例

 立即演示

interface MyInterface{
   public void sample();
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
   }
}

編譯時錯誤

InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method display() in MyInterface
public class InterfaceExample implements MyInterface{
       ^
1 error

但是,如果你仍需跳過實現。

  • 你可以透過丟擲一個異常(如 UnsupportedOperationException 或 IllegalStateException)來為不需要的方法提供一個虛擬實現。

示例

 立即演示

interface MyInterface{
   public void sample();
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public void display(){
      throw new UnsupportedOperationException();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}

輸出

Implementation of the sample method
Exception in thread "main" java.lang.UnsupportedOperationException
at InterfaceExample.display(InterfaceExample.java:10)
at InterfaceExample.main(InterfaceExample.java:15)
  • 你可以讓方法在介面本身中成為預設方法,自 Java8 起在介面中引入了預設方法,如果你在介面中擁有預設方法,則不必在實現類中覆蓋它們。

示例

 立即演示

interface MyInterface{
   public void sample();
   default public void display(){
      System.out.println("Default implementation of the display method");
   }
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}

輸出

Implementation of the sample method
Default implementation of the display method

更新於: 10-Sep-2019

7K+ 瀏覽

開始您的 職業生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.