如何在 Java 中仅重写接口的少数方法?

java 8object oriented programmingprogramming更新于 2025/4/15 9:07:17

从具体类实现接口后,您需要提供其所有方法的实现。如果您在编译时尝试跳过接口方法的实现,则会产生错误。

示例

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();
   }
}

Compile-time error

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

相关文章