如何重写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方法的默认实现
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西