如何重写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方法的默认实现
热门推荐
7 小托班祝福语简短
10 感恩跨年祝福语大全简短
11 高寿生日祝福语简短独特
12 女神节祝福语简短创意
13 春节红包祝福语大全简短
14 祝福语男性朋友简短大方
15 新年祝福语2026最简短
16 跟阿姨再见祝福语简短
17 母亲祝福语简短微信
18 初三新年祝福语简短