如果我们重载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 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短