如果我们重载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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬