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());
}
}
第一步: 在执行new WithFinalFields时候 先对类 WithFields进行加载 JMS调用static中的代码初始化类
第二步: 在调用 WithFinalFields 的 static final SelfCounter scsf = new SelfCounter();时候先对类
SelfCounter 进行加载
第三步: 初始化类SelfCounter 调用 private static int count = 0;
第四步: 实例化对象 scsf 会掉用类 SelfCounter 中的 private int id = count++ (到此步
类With FinalFields 的初始化工作完成, 因为count++是后++ 操作故 id=0)
第五步: 进行WithFinalFields类 对象的实例化操作。 执行 final SelfCounter scf = new SelfCounter();
第六步: 因为类SelfCounter已经加载 故只做对象的初始化 调用 private int id = count++;
(到此 整个 new WithFinalFields()操作才完成)
下一个new 操作 因为类已经加载, 故只要进行对象的初始化即可 所以static final SelfCounter scsf =
new SelfCounter();不会被再次的执行。
推荐看一篇不错的文章 关于类与对象的初始化的问题的
http://www.ibm.com/developerworks/cn/java/j-lo-clobj-init/!!