zoukankan      html  css  js  c++  java
  • Java笔记 #04# 类的初始化顺序补充

    参考 java中的类的初始化顺序详解

    package org.sample;
    
    class Bread {
        Bread() { System.out.println("Bread()"); }
    }
    class Cheese {
        Cheese() { System.out.println("Cheese()"); }
    }
    class Lettuce {
        Lettuce() { System.out.println("Lettuce()"); }
    }
    
    public class TestOrder {
    
        static {
            System.out.println("static block - 1 has been executed.");
        }
    
        {
            System.out.println("non-static - 1 block has been executed.");
        }
    
        private static final Bread bread = new Bread();
        private static final Cheese cheese = new Cheese();
        static {
            System.out.println("static block - 2 has been executed.");
        }
        private static final Lettuce lettuce = new Lettuce();
    
        private final Bread bread1 = new Bread();
        {
            System.out.println("non-static - 2 block has been executed.");
        }
        private final Cheese cheese1 = new Cheese();
        private final Lettuce lettuce1 = new Lettuce();
    
        public static void run() {
            System.out.println("run static method.");
        }
    
        public TestOrder() {
            System.out.println("create object.");
        }
    
        public static void main(String[] args) {
            TestOrder.run();
            new TestOrder();
        }
    }
    
    /*
    output=
    static block - 1 has been executed.
    Bread()
    Cheese()
    static block - 2 has been executed.
    Lettuce()
    run static method.
    non-static - 1 block has been executed.
    Bread()
    non-static - 2 block has been executed.
    Cheese()
    Lettuce()
    create object.
     */

    之所以补充上面的代码,主要是为了强调:【实例域以及初始化块】的执行也是依赖于代码书写顺序的(自上而下),而并非随机执行或者按照某种优先顺序。不过,一些特殊情况可能需要另当别论。



  • 相关阅读:
    hdoj 1175 (bfs)
    hdoj1072 Nightmare bfs
    hdoj1242(bfs+priority_queue)
    hdoj1242(dfs 剪枝 解法)
    hdoj1421(bfs)
    配置Windows 2008 R2 64位 Odoo 8.0 源码PyCharm开发调试环境
    [转]编译VC++程序warning C4819快速解决
    解决VS2013+IE11调试DevExpress ASP.NET MVC的性能问题
    Google被墙 Android开发工具下载地址
    Mac OS X Yosemite安装盘U盘制作
  • 原文地址:https://www.cnblogs.com/xkxf/p/9372483.html
Copyright © 2011-2022 走看看