public class Single {
private int num;
public void setNum(int num){
this.num =num;
}
public int getNum(){
return num;
}
private Single(){};
private static Single s=new Single();
public static Single getInstance(){
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Single s1=Single.getInstance();
Single s2=Single.getInstance();
s1.setNum(22);
System.out.println(s2.getNum());
System.out.println(s.num);
}
}
/**
* 在代码中 Single类中的num为类成员。构造函数私有,所以外部不能创建Single对象。
*在主函数中是将对象s赋给s1,s2, s1与s2都指向s对象的堆地址值。
*所以成员num有s1,s2,s三个引用
*/
|