码迷,mamicode.com
首页 > 其他好文 > 详细

问题1--static final关键词

时间:2018-04-21 17:35:20      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:++   public   field   man   cond   class   多少   turn   ret   

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

标签:++   public   field   man   cond   class   多少   turn   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!