如何重写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方法的默认实现
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志