I think your question has two parts:
1) Why the value of static variable b was not initialized and though
the value was initialized in the constructor?
Ans: First thing is that no constructor is called before main(). Constructors are called in main(). Whenever in main() you use new
as :
public static void main(String args[]){
MyClass myclass= new MyClass()
}
then only constructor is called.
In your code static variable b was not initialized becoz u are initializing it in constructor A() but this constructor has never been called. You can call A() constructor in your code as:
public static void main(String[] args) {
A a=new A(); // constructor gets called here.
b.func();
}
2) what is proper way of initializing a static variable?
The right way to initialize a static variable is to use static Initialization Blocks rather than to initialize them in constructors as shown in answer given by duffymo above.
static {
b = new B();
}
You can also use:
public class A {
private static B b = new B();
public A() {
}
public static void main(String[] args) {
b.func();
}
}
b
dependent upon the creation of an instance ofA
. – user1329572 May 9 '12 at 13:34