java接口方法都要重写_如何重写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方法的默认实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值