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.
The preferred ways to initialize static members are either (as mentioned before)
or for more complex initialization code you could use a static initializer block:
Your code should work. Are you sure you are posting your exact code?
You could also initialize it more directly :