静态变量初始化java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1642347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:35:53  来源:igfitidea点击:

static variable initialization java

javastaticinitialization

提问by Rohit Banga

how to initialize a private static member of a class in java.

如何在java中初始化类的私有静态成员。

trying the following:

尝试以下操作:

public class A {
   private static B b = null;
   public A() {
       if (b == null)
         b = new B();
   }

   void f1() {
         b.func();
   }
}

but on creating a second object of the class A and then calling f1(), i get a null pointer exception.

但是在创建 A 类的第二个对象然后调用 f1() 时,我得到一个空指针异常。

采纳答案by sfussenegger

The preferred ways to initialize static members are either (as mentioned before)

初始化静态成员的首选方法是(如前所述)

private static final B a = new B(); // consider making it final too

or for more complex initialization code you could use a static initializer block:

或者对于更复杂的初始化代码,您可以使用静态初始化程序块:

private static final B a;

static {
  a = new B();
}

回答by KLE

Your code should work. Are you sure you are posting your exact code?

您的代码应该可以工作。您确定要发布确切的代码吗?



You could also initialize it more directly :

您还可以更直接地初始化它:

    public class A {

      private static B b = new B();

      A() {
      }

      void f1() {
        b.func();
      }
    }