在Java中,如果我们重载接口的默认方法会发生什么?
Java中的接口类似于类,但是它只包含抽象方法和final和static的字段。
从Java 8开始,接口中引入了静态方法和默认方法。
默认方法 - 与其他抽象方法不同,这些方法可以有默认实现。如果接口中存在默认方法,则不需要在已实现此接口的类中重写(提供主体)它。
简而言之,您可以使用实现类的对象访问接口的默认方法。
示例
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
重写默认方法
不需要重写接口的默认方法,但是您仍然可以像重写超类的普通方法一样重写它们。但是,请确保在重写之前删除default关键字。
示例
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 Tutorialspoint");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
Hello welcome to Tutorialspoint
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP