English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

是否在Java的默认构造函数中初始化了静态变量?

静态文件/变量属于该类,它将与该类一起加载到内存中。您可以在不创建对象的情况下调用它们。(使用类名作为参考)。在整个类中只有一个静态字段的副本可用,即,静态字段的值在所有对象中都相同。您可以使用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

您不能从构造函数向最终变量赋值-

示例

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

初始化除声明语句以外的静态最终变量的唯一方法是静态块。

静块是代码使用静态关键字的块。通常,这些用于初始化静态成员。JVM在类加载时在main方法之前执行静态块。

示例

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