如何重写Java中仅有的几种接口方法?

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

示例

interface MyInterface{
   public void sample();
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Sample方法的实现");
   }
   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("Sample方法的实现");
   }
   public void display(){
      throw new UnsupportedOperationException();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}

输出结果

Sample方法的实现
Exception in thread "main" java.lang.UnsupportedOperationException
at InterfaceExample.display(InterfaceExample.java:10)
at InterfaceExample.main(InterfaceExample.java:15)
  • 您可以使方法在接口本身中成为默认方法,因为Java8以来在接口中引入了Default方法,如果接口中有默认方法,则在实现类中不必强制覆盖它们。

示例

interface MyInterface{
   public void sample();
   default public void display(){
      System.out.println("Display方法的默认实现");
   }
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Sample方法的实现");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}

输出结果

Sample方法的实现
Display方法的默认实现