為什麼Java介面即使可以單獨擁有靜態方法,卻不能有靜態初始化塊呢?
Java中的介面類似於類,但它只包含抽象方法和宣告為final和static的欄位。
靜態方法使用static關鍵字宣告,它將與類一起載入到記憶體中。您可以使用類名訪問靜態方法,而無需例項化。
Java 8 中的介面靜態方法
從Java 8開始,您可以在介面中擁有靜態方法(帶方法體)。您需要使用介面名稱來呼叫它們,就像類的靜態方法一樣。
示例
在下面的示例中,我們在介面中定義了一個靜態方法,並從實現該介面的類中訪問它。
interface MyInterface{
public void demo();
public static void display() {
System.out.println("This is a static method");
}
}
public class InterfaceExample{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
MyInterface.display();
}
}輸出
This is the implementation of the demo method This is a static method
靜態塊
靜態塊是一段帶有static關鍵字的程式碼塊。通常,它們用於初始化靜態成員。JVM在類載入時,在main方法之前執行靜態塊。
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}輸出
Hello this is a static block This is main method
介面中的靜態塊
主要的是,如果您在宣告時沒有初始化類/靜態變數,則可以使用靜態塊來初始化它們。
對於介面,當您在其中宣告一個欄位時,必須為其賦值,否則會生成編譯時錯誤。
示例
interface Test{
public abstract void demo();
public static final int num;
}編譯時錯誤
Test.java:3: error: = expected public static final int num; ^ 1 error
當您為介面中的static final變數賦值時,這將得到解決。
interface Test{
public abstract void demo();
public static final int num = 400;
}因此,介面中不需要靜態塊。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP