在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