Java 中靜態構造器的替代方案是什麼?
Java 中構造器的主要目的是初始化類的例項變數。
但是,如果一個類具有靜態變數,則不能使用構造器來初始化它們(可以在構造器中為靜態變數賦值,但在這種情況下,我們只是在為靜態變數賦值)。因為靜態變數在例項化之前(即在呼叫構造器之前)就被載入到記憶體中。
因此,應該從靜態上下文中初始化靜態變數。構造器前面不能使用 static 關鍵字,因此,作為替代方案,可以使用靜態塊來初始化靜態變數。
靜態塊
靜態塊是一個帶有 static 關鍵字的程式碼塊。通常,它們用於初始化靜態成員。JVM 在類載入時,在 main 方法之前執行靜態塊。
示例
在下面的 Java 程式中,Student 類有兩個靜態變數 *name* 和 *age*。
在這裡,我們使用 **Scanner** 類從使用者讀取 name 和 age 值,並從靜態塊初始化靜態變數。
import java.util.Scanner; public class Student { public static String name; public static int age; static { Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); name = sc.nextLine(); System.out.println("Enter the age of the student: "); age = sc.nextInt(); } public void display(){ System.out.println("Name of the Student: "+Student.name ); System.out.println("Age of the Student: "+Student.age ); } public static void main(String args[]) { new Student().display(); } }
輸出
Enter the name of the student: Ramana Enter the age of the student: 16 Name of the Student: Ramana Age of the Student: 16
廣告