public class TestSingle
{
private static final TestSingle onlyone =new TestSingle(); public static TestSingle getsingle()
{
return onlyone;
}
private TestSingle(){}
} 我知道final是阻止变量内容被修改,但是onlyone中保存的只是一个TestSingle类的对象的首地址,并不是直接保存的内容,所以这个地址的内容是可以改的,也就是说它还可以指向别的对象,不知道我这么理解对不对?
{
private static final TestSingle onlyone =new TestSingle(); public static TestSingle getsingle()
{
return onlyone;
}
private TestSingle(){}
} 我知道final是阻止变量内容被修改,但是onlyone中保存的只是一个TestSingle类的对象的首地址,并不是直接保存的内容,所以这个地址的内容是可以改的,也就是说它还可以指向别的对象,不知道我这么理解对不对?
that's the rule.
TestSingle another = new TestSingle();
onlyone = anohter;但被onlyone所引用的对象状态可以发生变化,假设TestSingle类有一个公开属性:
public String attr = null;可以通过onlyone.attr = "new String attribute";来改变被引用的对象(的状态)
-------------------------------无愧我心大侠能再解释的详细点吗,为什么这样就只能生成一个对象呢?如果我调用2次new TestSingle(),TestSingle A= new TestSingle();
TestSingle B= new TestSingle();
A.getSinge()!= B.getSingle()?
只能通过getSingle
final 的内容不可能被更改,可以见如下测试.public class TestSingle
{
public static TestSingle refOnlyone = new TestSingle();
private static final TestSingle onlyone = refOnlyone; public static TestSingle getsingle()
{
return onlyone;
}
private TestSingle(){
}
public static void setTestSingleNull()
{
refOnlyone = null;
}
public static void main(String[] args)
{
System.out.println("onlyone\t\t"+TestSingle.onlyone);
System.out.println("refOnlyone\t"+TestSingle.refOnlyone);
// 清除并立刻垃圾回收!
TestSingle.setTestSingleNull();
System.gc();
// 重新输出
System.out.println("onlyone\t\t"+TestSingle.onlyone);
System.out.println("refOnlyone\t"+TestSingle.refOnlyone);
}
}onlyone引用refOnlyone对象.但是设置refOnlyone = Null,并不会使onlyone变成nullF:\>javac TestSingle.javaF:\>java TestSingle
onlyone TestSingle@bd0108
refOnlyone TestSingle@bd0108
onlyone TestSingle@bd0108
refOnlyone null
PS:不对之处,请楼下指出,学习学习. : )
而是onlyone被初始化成与refOnlyone一样的值
这个值实际上指向new TestSingle();这个新申请的这段内存如果你学过c++,这与指针类似A * pa1 = new A;
A * pa2 = pa1;
pa1 = NULL;