一般来说在类加载的时候是先加载静态的再加载非静态的,所以静态不能访问非静态的
但是是不是跟单例模式有矛盾呢:
private NumberMachine() {
}
private static NumberMachine instance = new NumberMachine();
public static NumberMachine getInstance() {
return instance;
}
再看看下面这个问题:
class Date {
// 下面两行代码换位置结果就会出现不同
private static int mx = 0;
private static final Date mInstance = new Date();
private Date() {
System.out.println("mx=" + mx);
mx = getVersion();
}
public static Date getInstance() {
return mInstance;
}
public int getVersion() {
int v = 0;
if (v == 0) {
v = 7;
}
return v;
}
public int getmx() {
return mx;
}
}
public class TestStatic {
public static void main(String args[]) {
System.out.println(Date.getInstance().getmx());
}
}
求解释! |