public class TestSingle
{
  private static final TestSingle onlyone =new TestSingle();     public static TestSingle getsingle()
     {
       return onlyone;
      }
     private TestSingle(){}
} 我知道final是阻止变量内容被修改,但是onlyone中保存的只是一个TestSingle类的对象的首地址,并不是直接保存的内容,所以这个地址的内容是可以改的,也就是说它还可以指向别的对象,不知道我这么理解对不对? 
     

解决方案 »

  1.   

    no, onlyone could only point to where it's inited.
    that's the rule.
      

  2.   

    不对,加上final以后,onlyone就不能再引用其他对象了,换句话说,再也无法对onlyone进行赋值操作,比如下面的代码就是错误的:
    TestSingle another = new TestSingle();
    onlyone = anohter;但被onlyone所引用的对象状态可以发生变化,假设TestSingle类有一个公开属性:
    public String attr = null;可以通过onlyone.attr = "new String attribute";来改变被引用的对象(的状态)
      

  3.   

    加了final不能再引用其他的对象了,对象的地址不能再改变了,内容可以发生变化。
      

  4.   

    onlyone对象内的域变量的值是可以改变的
      

  5.   

    其实很容易理解,这是模式中的单例模式,也就是只能生成该类的一个对象。
    -------------------------------无愧我心大侠能再解释的详细点吗,为什么这样就只能生成一个对象呢?如果我调用2次new TestSingle(),TestSingle A= new TestSingle();
    TestSingle B= new TestSingle();
    A.getSinge()!= B.getSingle()?
      

  6.   

    这个就是单例模式,因为constructor为私有的,你无法new
    只能通过getSingle
      

  7.   

    能不能举个例子告诉我怎么把内容改变?-----------------
    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:不对之处,请楼下指出,学习学习.  : ) 
      

  8.   

    onlyone并不是引用refOnlyone对象
    而是onlyone被初始化成与refOnlyone一样的值
    这个值实际上指向new TestSingle();这个新申请的这段内存如果你学过c++,这与指针类似A * pa1 = new A;
    A * pa2 = pa1;
    pa1 = NULL;
      

  9.   

    没有注意到constructor是private,谢谢   xzgyb(老达摩) !!!