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

实例变量的初始化

但是,如果声明一个静态且最终的实例变量,Java 编译器不会在默认构造函数中初始化它,因此必须初始化静态且最终的变量。如果不初始化,则会生成编译时错误。

示例

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

除了声明语句之外,初始化静态 final 变量的唯一方法是静态块。

**静态块**是一个带有 static 关键字的代码块。通常,它们用于初始化静态成员。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

更新于:2020年11月19日

6K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.