//code_1
public class SingleInstance {
private static SingleInstance si = new SingleInstance(); //注意这里
public static int num_1;
public static int num_2 = 0;
public SingleInstance() {
num_1 ++;
num_2 ++;
}
public static SingleInstance getInstance() {
return si;
}
public void print() {
System.out.println(num_1 + ":" + num_2);
}
public static void main(String[] args) {
SingleInstance.getInstance().print();
}
}
结果: 1:1 1:0
//code_2
public class SingleInstance {
public static int num_1;
public static int num_2 = 0;
private static SingleInstance si = new SingleInstance(); //注意,跟上面不一样了
public SingleInstance() {
num_1 ++;
num_2 ++;
}
public static SingleInstance getInstance() {
return si;
}
public void print() {
System.out.println(num_1 + ":" + num_2);
}
public static void main(String[] args) {
SingleInstance.getInstance().print();
}
结果: 1:1 1:1
} //code_3
public class SingleInstance {
private static SingleInstance si = new SingleInstance(); //注意这里
public int num_1;
public int num_2 = 0;
public SingleInstance() {
num_1 ++;
num_2 ++;
}
public static SingleInstance getInstance() {
return si;
}
public void print() {
System.out.println(num_1 + ":" + num_2);
}
public static void main(String[] args) {
SingleInstance.getInstance().print();
}
结果: 1:1 1:1
能给分析一下上面3段代码的结果是怎么得到的吗?
}
|
|