package 第六章.第六章练习;
class SelfCounter {
private static int count = 0;
private int id = count++;
public SelfCounter(String type){
System.out.println(count+":count的值");
System.out.println(type+":type");//判断是先执行了谁
System.out.println(id+":id的值");
}
public String toString() {
return "SelfCounter " + id;
}
}
class WithFinalFields {
final SelfCounter scf = new SelfCounter("scf");
static final SelfCounter scsf = new SelfCounter("scsf"); //static 只初始化一次 而且是最先初始化的 不会再执行第二次了
public String toString() {
return "scf = " + scf + "\n"+
"scsf = " + scsf;
}
}
public class Test19 {
public static void main(String args[]) {
System.out.println("First object:");
System.out.println(new WithFinalFields()+"\n");
System.out.println("Second object:");
System.out.println(new WithFinalFields());
}
}
/**
* 执行后的结果
* First object:
1:count的值
scsf:type
0:id的值
2:count的值
scf:type
1:id的值
scf = SelfCounter 1
scsf = SelfCounter 0
Second object:
3:count的值
scf:type
2:id的值
scf = SelfCounter 2
scsf = SelfCounter 0
*/