看到一个程序讲final与static final的区别,
class SelfCounter{
private static int counter;
private int id = counter ++;
public String toString(){
return "SelfCounter :" + id;
}
}class WithFinalFields{
static final SelfCounter wffs = new SelfCounter();
final SelfCounter wff = new SelfCounter();
public String toString(){
return "wff = " + wff + "\n wffs = " + wffs;
}
}public class E18_StaticFinal {
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 :
wff = SelfCounter :1
wffs = SelfCounter :0
Second Object:
wff = SelfCounter :2
wffs = SelfCounter :0 ,不太明白为什么两次wffs=SelfCounter:0,
我感觉counter被初始化为0后,id会自增为1,为什么声明为static final的对象后,id就是0?望高人指点
class SelfCounter{
private static int counter;
private int id = counter ++;
public String toString(){
return "SelfCounter :" + id;
}
}class WithFinalFields{
static final SelfCounter wffs = new SelfCounter();
final SelfCounter wff = new SelfCounter();
public String toString(){
return "wff = " + wff + "\n wffs = " + wffs;
}
}public class E18_StaticFinal {
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 :
wff = SelfCounter :1
wffs = SelfCounter :0
Second Object:
wff = SelfCounter :2
wffs = SelfCounter :0 ,不太明白为什么两次wffs=SelfCounter:0,
我感觉counter被初始化为0后,id会自增为1,为什么声明为static final的对象后,id就是0?望高人指点
wffs这个字段可以理解为单例,就是只存在唯一一个,不管你new多少对象,这个字段都是唯一的,而且不会变的
这个不管你建多少对象都是公用的一个 wffs
final SelfCounter wff = new SelfCounter();
只在你第一次调用该类的时候被实例化, 它是一个类变量, 而非实例变量。 所以以后不管你new了多少对象,它们都用同一个类变量。
final是不可变,但问题是有两个WithFinalFields对象,每个WithFinalFields对象都有它自己的wff常量,而且对于引用类型的常量,所谓不可变仅仅是引用不能重新指向其他对象,而不是对象内部的各种属性的值不可变。