开发者

static variable initialization java

开发者 https://www.devze.com 2022-12-09 14:40 出处:网络
how to initialize a private static member of a clas开发者_StackOverflow中文版s in java. trying the following:

how to initialize a private static member of a clas开发者_StackOverflow中文版s 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.


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();
}


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();
      }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号