Pun*_*Raj 2 java static constructor
我想从下面的代码中理解y静态变量b的值没有初始化,尽管值在构造函数中初始化.
public class A {
private static B b = null;
public A() {
if (b == null)
b = new B();
}
public static void main(String[] args) {
b.func();
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢Punith
错了 - 这样做:
public class A {
private static B b = null;
static {
b = new B();
}
public A() {
}
public static void main(String[] args) {
b.func();
}
}
Run Code Online (Sandbox Code Playgroud)
你永远不会调用A()构造函数.main函数是静态的,这意味着它不属于A的实例.所以当你输入main时,没有创建A的实例,所以从未调用过构造函数而b仍为null.
如果运行此代码,则应该获得NullPointerException.
如果添加新的A(); 在b.func()之前; 然后你会没事的(代码仍然是奇怪的)