参考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.
*/

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

最新文章

  1. NSString asscii格式(2进制) 转 utf8格式——解决iOS自己处理http socket数据,遇到Transfer-Encoding: chunked时
  2. django admin.py settings 操作
  3. java工程师联通XX面试题目
  4. 【2017集美大学1412软工实践_助教博客】团队作业6——展示博客(Alpha版本)
  5. 201521123042 《Java程序设计》第3周学习总结
  6. TIBCO EMS安装部署
  7. Android群英传笔记——第十章:Android性能优化
  8. 安卓学习 intent
  9. php中对象赋值问题
  10. A1059. Prime Factors
  11. Ubuntu 重新安装声卡驱动
  12. 两个或多个线程执行完成之后继续执行之后的步骤,CountDownLatch与CyclicBarrier
  13. 009 HDFS的shell命令(里面有一个安全模式)
  14. emacs之配置auto-complete
  15. tyvj 1091 等差数列 dp
  16. Python-学习-小例子练习
  17. 并查集——poj2236(带权并查集)
  18. juniper常用命令
  19. vue v-if with v-for
  20. Singleton patterns 单件(创建型模式)

热门文章

  1. 基于nodejs的 本地文件夹http服务器:http-server
  2. Centos7 下 yum -y install ntp 出现/var/run/yum.pid 已被锁定
  3. java实现的加密解密
  4. TortoiseGit推送代码到Gerrit的过程
  5. GBDT调参总结
  6. Sql Server 生成连续时间段
  7. cocos2dx 3.x 网络循环接收数据(RakNet::Packet* packet)单步网络接收
  8. git add -A -u . 的区别
  9. react基础&JSX基础
  10. 前端forEach在Array、map、set中的使用,weakset,weakmap