java方法重写默认_是否必须重写Java中接口的默认方法?

从Java8开始,默认方法在接口中引入。与其他抽象方法不同,这些方法可以具有默认实现。如果您在接口中具有默认方法,则不必在已经实现此接口的类中重写(提供正文)。

简而言之,您可以使用实现类的对象来访问接口的默认方法。

示例interface MyInterface{

public static int num = 100;

public default void display() {

System.out.println("display method of MyInterface");

}

}

public class InterfaceExample implements MyInterface{

public static void main(String args[]) {

InterfaceExample obj = new InterfaceExample();

obj.display();

}

}

输出结果display method of MyInterface

但是,当您的类实现两个接口,并且它们都具有名称和原型相同的方法时。您必须重写此方法,否则会生成编译时错误。

示例interface MyInterface1{

public static int num = 100;

public default void display() {

System.out.println("display method of MyInterface1");

}

}

interface MyInterface2{

public static int num = 1000;

public default void display() {

System.out.println("display method of MyInterface2");

}

}

public class InterfaceExample implements MyInterface1, MyInterface2{

public static void main(String args[]) {

InterfaceExample obj = new InterfaceExample();

//obj.display();

}

}

编译时错误InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2

public class InterfaceExample implements MyInterface1, MyInterface2{

^

1 error

为了解决这个问题,您需要重写display()实现类中的一个(或两个)方法-

示例interface MyInterface1{

public static int num = 100;

public default void display() {

System.out.println("display method of MyInterface1");

}

}

interface MyInterface2{

public static int num = 1000;

public default void display() {

System.out.println("display method of MyInterface2");

}

}

public class InterfaceExample implements MyInterface1, MyInterface2{

public void display() {

MyInterface1.super.display();

//或

MyInterface2.super.display();

}

public static void main(String args[]) {

InterfaceExample obj = new InterfaceExample();

obj.display();

}

}

输出结果display method of MyInterface1

display method of MyInterface2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值