问题1--static final关键词
Posted 小熊hit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了问题1--static final关键词相关的知识,希望对你有一定的参考价值。
如下面所述代码,scf输出scf = SelfCounter id,后面id递增,可以理解。而由于scsf被static final修饰了,无论再new多少次输出都不会变,但是为什么输出是0而不是1呢?百思不得解,小白求拍求解答!
class SelfCounter {
private static int count;
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 Final_Static {
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());
System.out.println("Third object:");
System.out.println(new WithFinalFields());
}
}/* Output:
First object:
scf = SelfCounter 1
scsf = SelfCounter 0
Second object:
scf = SelfCounter 2
scsf = SelfCounter 0
*///:~
以上是关于问题1--static final关键词的主要内容,如果未能解决你的问题,请参考以下文章
Java_基础java中static与final关键字的区别