static variable initialization java

2019-01-22 11:00发布

how to initialize a private static member of a class in 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.

2条回答
Animai°情兽
2楼-- · 2019-01-22 11:34

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();
}
查看更多
【Aperson】
3楼-- · 2019-01-22 11:53

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();
      }
    }
查看更多
登录 后发表回答