我們能否在 Java 定義一個靜態構造器?
否,我們不能在 Java 中定義靜態構造器,如果我們試圖使用 static 關鍵字來定義構造器,將發生編譯器錯誤。
一般來說,static 表示類級別。構造器用於為例項變數分配初始值。static 和構造器既不同又相反。我們需要為例項變數分配初始值,可以使用構造器。我們需要分配靜態變數,可以使用靜態程式碼塊。
示例
public class StaticConstructorTest { int x = 10; // Declaratiopn of Static Constructor static StaticConstructorTest() { System.out.println("Static Constructor"); } public static void main(String args[]) { StaticConstructorTest sct = new StaticConstructorTest(); } }
在以上示例中,我們建立了一個靜態構造器。程式碼不會編譯,並且會丟擲錯誤,指出此處不允許修飾符 static。
輸出
StaticConstructorTest.java:4: error: modifier static not allowed here
廣告