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 only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.
As static variables are initialized only once and are shared by all objects of a class, the static variables are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With