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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP