类的初始化与对象的初始化

class SelfCounter {
  private static int count = 0;
  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 E18_FinalFields {
  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());
  }
}

第一步: 在执行new WithFinalFields时候 先对类 WithFields进行加载 JMS调用static中的代码初始化类

 

第二步: 在调用  WithFinalFields 的 static final SelfCounter scsf = new SelfCounter();时候先对类
SelfCounter 进行加载 

 

第三步:  初始化类SelfCounter 调用 private static int count = 0;

 

第四步:  实例化对象 scsf  会掉用类 SelfCounter 中的  private int id = count++ (到此步

类With FinalFields 的初始化工作完成,  因为count++是后++ 操作故  id=0)

 

第五步:  进行WithFinalFields类 对象的实例化操作。 执行 final SelfCounter scf = new SelfCounter();

第六步: 因为类SelfCounter已经加载 故只做对象的初始化 调用  private int id = count++;

(到此 整个 new WithFinalFields()操作才完成)

 

下一个new 操作 因为类已经加载,  故只要进行对象的初始化即可  所以static final SelfCounter scsf =
    new SelfCounter();不会被再次的执行。

 

推荐看一篇不错的文章   关于类与对象的初始化的问题的

 

     http://www.ibm.com/developerworks/cn/java/j-lo-clobj-init/!! 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值