zoukankan      html  css  js  c++  java
  • java语句顺序有时非常重要

    我们学习java时,通常被告知,变量定义的顺序不重要,可是下面程序确在jdk 1.7上执行出错。

    public class FactoryImpl implements Serializable {
        private final static  FactoryImpl INSTANCE = new FactoryImpl();
        private final static AtomicInteger count = new AtomicInteger(0);
    
        private int id;
    
        private FactoryImpl() {
            id = count.incrementAndGet();
        }
    
        public int getId() {
            return id;
        }
    
        public static FactoryImpl getInstance() {
            return INSTANCE;
        }
    
        public static void main(String[] args) {
            FactoryImpl impl1 = FactoryImpl.getInstance();
            System.out.println(impl1.id);
        }
    }

    把下面代码调整顺序之后能够运行成功。

        private static final FactoryImpl INSTANCE = new FactoryImpl();
        private final static AtomicInteger count = new AtomicInteger(0);

    原因例如以下,假设不调整时,当类被载入时,先初始化INSTANCE静态变量,这时,会调用FactoryImpl构造方法,在此构造方法里,调用count.incremnetAndGet();这时count还没有初始化。这是因为进行类载入时。静成变量的初始化顺序造成的。

  • 相关阅读:
    Sum Root to Leaf Numbers [LeetCode]
    Symmetric Tree [LeetCode]
    Combination Sum II [LeetCode]
    Maximal Rectangle [LeetCode]
    Trapping Rain Water [LeetCode]
    Combination Sum [LeetCode]
    05 如何“响铃”
    04 八进制
    03 关键字?保留字?预留字?
    020 函数之变量的作用域
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7134212.html
Copyright © 2011-2022 走看看