日期:2014-05-20  浏览次数:20819 次

一个关于 static 和final的程序 看不明白了 谁知道呢?
class SelfCounter {
  private static int count = 0;
  private int id = count++;
  public String toString() {
  return "SelfCounter " + id;
  }
}

class WithFinalFields {
  final SelfCounter scf = new SelfCounter();
  static final SelfCounter scsf = new SelfCounter();
  public String toString() {
  return "scf = " + scf + "\nscsf = " + scsf;
  }
}

public class E18_FinalFields {
  public static void main(String args[]) {
  System.out.println("First object:");
  System.out.println(new WithFinalFields());
  System.out.println("Second object:");
  System.out.println(new WithFinalFields());
  }
} ///:~

输出结果是:
First object:
scf = SelfCounter 1
scsf = SelfCounter 0
Second object:
scf = SelfCounter 2
scsf = SelfCounter 0

就是看不明白输出结果,第一个System.out.println(new WithFinalFields()); 我还能看明白,初始化之后知道先输出SelfCounter 1,但是static final SelfCounter scsf = new SelfCounter();初始化我就看不明白了 输出结果为什么是SelfCounter 0????

第二个System.out.println(new WithFinalFields()); 比较疑惑,还是static final SelfCounter scsf = new SelfCounter();这一块不明白!!!!!!

谁知道 static final SelfCounter scsf = new SelfCounter();是怎么一回事 请指点我一下 谢谢了!!!




------解决方案--------------------
你首先要搞清楚对象的初始化顺序。
对象在第一次初始化的时候是先执行静态的部分,包括静态变量和静态初始化块中的语句。而且静态的对象初始化的时候静态的是只初始化一次。

所以
Java code

class WithFinalFields {
  final SelfCounter scf = new SelfCounter();
  static final SelfCounter scsf = new SelfCounter();
  public String toString() {
  return "scf = " + scf + "\nscsf = " + scsf;
  }
}

------解决方案--------------------
执行顺序
WithFinalFields.java-->static final SelfCounter scsf = new SelfCounter();
WithFinalFields.java-->final SelfCounter scf = new SelfCounter();
WithFinalFields.java-->final SelfCounter scf = new SelfCounter();
其实你的疑惑和final没有什么关系...final仅表示变量指向的对象引用不可变.....