如果我们重载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 我要结婚祝福语简短
18 婚前女儿生日祝福语简短