Java 中的静态变量是否在默认构造函数中初始化?
java 8object oriented programmingprogramming
静态字段/变量属于类,它将与类一起加载到内存中。您可以在不创建对象的情况下调用它们。(使用类名作为引用)。整个类中只有一个静态字段副本可用,即静态字段的值在所有对象中都是相同的。您可以使用 static 关键字定义静态字段。
示例
public class Sample{
static int num = 50;
public void demo(){
System.out.println("Value of num in the demo method "+ Sample.num);
}
public static void main(String args[]){
System.out.println("Value of num in the main method "+ Sample.num);
new Sample().demo();
}
}
输出
Value of num in the main method 50 Value of num in the demo method 50
静态变量的初始化
如果您在类中声明静态变量,但尚未初始化它们,就像实例变量一样,编译器会在默认构造函数中使用默认值初始化它们。
示例
public class Sample{
static int num;
static String str;
static float fl;
static boolean bool;
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
输出
0 null 0.0 false
实例变量的初始化
但是,如果您将实例变量声明为 static 和 final,Java 编译器将不会在默认构造函数中对其进行初始化,因此,必须初始化 static 和 final 变量。如果不这样做,将生成编译时错误。
示例
public class Sample{
final static int num;
final static String str;
final static float fl;
final static boolean bool;
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
编译时错误
Sample.java:2: error: variable num not initialized in the default constructor final static int num; ^ Sample.java:3: error: variable str not initialized in the default constructor final static String str; ^ Sample.java:4: error: variable fl not initialized in the default constructor final static float fl; ^ Sample.java:5: error: variable bool not initialized in the default constructor final static boolean bool; ^ 4 errors
不能从构造函数中为 final 变量赋值 −
示例
public class Sample{
final static int num;
Sample(){
num =100;
}
}
输出
Sample.java:4: error: cannot assign a value to final variable num num =100; ^ 1 error
除了声明语句之外,初始化静态最终变量的唯一方法是静态块。
静态块是带有 static 关键字的代码块。一般来说,它们用于初始化静态成员。JVM 在类加载时在主方法之前执行静态块。
示例
public class Sample{
final static int num;
final static String str;
final static float fl;
final static boolean bool;
static{
num =100;
str= "krishna";
fl=100.25f;
bool =true;
}
public static void main(String args[]){
System.out.println(Sample.num);
System.out.println(Sample.str);
System.out.println(Sample.fl);
System.out.println(Sample.bool);
}
}
输出
100 krishna 100.25 true

