zoukankan      html  css  js  c++  java
  • Java-JVM 类的初始化

    public class Test {
        protected static final Logger logger = LoggerFactory.getLogger(Test.class);
    
        public static void main(String[] args) {
            Singleton singleton = Singleton.getInstance();
            logger.info("counter1:" + singleton.counter1);
            logger.info("counter2:" + singleton.counter2);
        }
    }
    
    class Singleton {
        private static Singleton singleton = new Singleton();
        public static int counter1;
        public static int counter2 = 0;
    
        private Singleton() {
            counter1++;
            counter2++;
        }
    
        public static Singleton getInstance() {
            return singleton;
        }
    }

    Singleton singleton = Singleton.getInstance();这行代码首先给Singleton中的变量赋予默认的初始值:

    即:private static Singleton singleton的singleton赋予默认初始值null、

    public static int counter1 的counter1赋予默认初始值0、

    public static int counter2 的counter2赋予默认初始值0(不是显式的0)、

    然后会显式地给变量赋值:

    private static Singleton singleton的singleton赋予new Singleton(),此时会执行Singleton类的构造函数:

    private Singleton(){

    counter1++;

    counter2++;

    }

    counter1 = 1;

    counter2 = 1;

    接着给counet1、counter2显式赋值

    public static int counter1 ;

    public static int counter2 = 0;

    由于counter1没有显式值

    所以赋值完成后counter1 = 1、counter2 = 0;

    最后输出为counter1 = 1、counter2 = 0;

    如果把 private static Singleton singleton = new Singleton();放在 public static int counter2 = 0;的后面,则会输出counter1 = 1、counter2 = 1;

  • 相关阅读:
    HDU 1002 大数A+B
    HDU 2066 一个人的旅行(最短路)
    HDU 1869 六度分离(最短路 floyd)
    HDU 1159 Common Subsequence(LCS)
    POJ 3061 Subsequence(尺取法)
    NYOJ 10 skiing(记忆化搜索)
    dedecms添加全站的rss订阅功能
    dedecms artlist读取全站最新文章
    dedecms的title怎么优化?
    DedeCMS提示Maximum execution time of 30 seconds exceeded in解决办法
  • 原文地址:https://www.cnblogs.com/y8932809/p/8990975.html
Copyright © 2011-2022 走看看