Java 中静态构造函数还有其他解决方案吗?
java 8object oriented programmingprogramming
Java 中构造函数的主要目的是初始化类的实例变量。
但是,如果类中有静态变量,则无法使用构造函数初始化它们(虽然可以在构造函数中为静态变量赋值,但在这种情况下,我们只是在为静态变量赋值)。因为静态变量在实例化之前(即在调用构造函数之前)就已加载到内存中。
因此,我们应该在静态上下文中初始化静态变量。我们不能在构造函数之前使用静态方法。因此,作为替代方案,您可以使用静态块来初始化静态变量。
静态块
静态块是带有 static 关键字的代码块。通常,它们用于初始化静态成员。 JVM 在类加载时,会在主方法之前执行静态块。
示例
在下面的 Java 程序中,Student 类有两个静态变量 name 和 age。
在本程序中,我们使用 Scanner 类读取用户的姓名和年龄值,并通过静态块初始化这些静态变量。
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