我们可以在 Java 中覆盖默认方法吗?
Java 中的接口与类类似,但是只包含最终且为静态的抽象方法和字段。
自从 Java8 之后,在接口中引入了静态方法和默认方法。与其他抽象方法不同,这些方法可以拥有默认实现。如果在接口中有默认方法,那么在已经实现该接口的类中覆盖(提供主体)该方法并不是必须的。
简而言之,你可以使用实现类的对象来访问接口的默认方法。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
display method of MyInterface
覆盖默认方法
你可以在实现类中覆盖接口的默认方法。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
display method of class
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP