如果我们重载Java接口的默认方法会发生什么?
Java中的接口类似于类,但是它只包含final和static的抽象方法和字段。
由于Java8在接口中引入了静态方法和默认方法。
默认方法-与其他抽象方法不同,这些是可以具有默认实现的方法。如果接口中有默认方法,则在已实现此接口的类中重写(提供正文)不是强制性的。
简而言之,您可以使用实现类的对象来访问接口的默认方法。
示例
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 static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出结果
Default implementation of the display method
覆盖默认方法
强制覆盖接口的默认方法不是强制性的,但是仍然可以像超类的常规方法一样覆盖它们。但是,请确保删除默认关键字。
示例
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 Nhooo");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出结果
Hello welcome to Nhooo
热门推荐
10 答谢生子祝福语简短独特
11 送姐姐的话祝福语简短
12 中医经典祝福语大全简短
13 朋友祝福语卡片简短大气
14 520送给女友祝福语简短
15 学生国庆简短的祝福语
16 过年送礼祝福语简短精辟
17 送男友2026祝福语简短
18 给新生的简短祝福语