如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP