如果我们在 Java 中重载接口的默认方法会发生什么?
java 8object oriented programmingprogramming更新于 2025/11/15 11:24:17
Java 中的接口类似于类,但它只包含 final 和 static 的抽象方法和字段。
自 Java 8 以来,接口中引入了静态方法和默认方法。
默认方法 − 与其他抽象方法不同,这些方法可以具有默认实现。如果接口中存在默认方法,则无需在已实现此接口的类中重写(提供方法体)。
简而言之,您可以使用实现类的对象访问接口的默认方法。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display 方法的默认实现");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
输出
display 方法的默认实现
重写默认方法
接口的默认方法并非强制重写,但您仍然可以像重写超类的普通方法一样重写它们。但请确保删除它们前面的 default 关键字。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("Default implementation of the display method");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("Hello welcome to Tutorialspoint");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
输出
Hello welcome to Tutorialspoint

