首页 > 其他 > 详细

问题1--static final关键词

时间:2018-04-21 16:45:39      阅读:175      评论:0      收藏:0      [点我收藏+]

如下面所述代码,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关键词

原文:https://www.cnblogs.com/xiaoxionganna/p/8901891.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!