JAVA static 装载顺序

/**
 * 类加载顺序:
 * 1.加载类的静态属性(非静态不管)
 * 这里加载的是:public static int k = 0;
 * 然后加载:public static StaticLoadTest t1 = new StaticLoadTest("t1");
 * 因为此处进行了类的实例化所以
 * 1.1加载类的非静态属性
 * 这里是:public int j = print("j");
 * 运行完这个方法接着
 * 1.2顺序加载类中的非static代码块(static暂时不加载)
 * 这里是:print("构造快");和print("静态块");
 * 运行完接着
 * 1.3加载类的构造方法
 * 这里是:public StaticTest(String str)
 * 运行完(一个静态属性的实例就完成了)
 * 2.继续加载类的静态属性
 * 这里加载的是:public static StaticLoadTest t2 = new StaticLoadTest("t2");
 * 2.1重复(1.1-1.3)
 * 3.继续加载类的静态属性
 * 这里加载的是:public static int i = print("i");
 * 运行完接着
 * 4.继续加载类的静态属性
 * 这里加载的是:public static int n = 99;
 * 不管你n原来是多少现在为99
 * 接着
 * 5.(如果有static代码块,在这里先加载,这个里面没有所以加载主函数)加载主函数
 * 这里加载的是:StaticLoadTest t = new StaticLoadTest("init");
 * 因为此处进行了类的实例化所以
 * 5.1
 * 重复1.1-1.3
 * 5.2
 * 因为public static int print(String str)这个方法返回++n
 * 所以n从99开始累加
 * 运行完OK了
 *
 * @Author wangwei-ww
 * @Date 2017/7/24 20:19
 * @Comment
 */
public class StaticLoadTest {
    public static int k = 0;
    public static StaticLoadTest t1 = new StaticLoadTest("t1");
    public static StaticLoadTest t2 = new StaticLoadTest("t2");
    public static int i = print("i");
    public static int n = 99;
    public int j = print("j");

    {
        print("构造快");
    }

    {
        print("静态块");
    }

    public StaticLoadTest(String str) {
        System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
        ++n;
        ++i;
    }

    public static int print(String str) {
        System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
        ++i;
        return ++n;
    }

    private static class SingletonHolder {
        static StaticLoadTest instance = new StaticLoadTest("static-inner-class");
    }

    public static StaticLoadTest getInstance() {
        return StaticLoadTest.SingletonHolder.instance;
    }

    public static void main(String[] args) {
        StaticLoadTest t = new StaticLoadTest("init");
        StaticLoadTest.getInstance();
    }
}

转载于:https://my.oschina.net/jsycwangwei/blog/1486542

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值