是否强制要求在 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();
//or,
MyInterface2.super.display();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
display method of MyInterface1 display method of MyInterface2
广告
数据结构
网络技术
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP