目录
父类静态代码块(static) ->
子类静态代码块(static) ->
父类非静态代码块 ->
父类构造函数 ->
子类非静态代码块 ->
子类构造函数
tips:
- 执行遵循static优先原则
- 静态代码块在类加载时执行,类加载在编译阶段(生成.class文件)完成,即只一次运行只执行一次
- 当new对象的时候,从上至下执行一次非静态初始化语句和初始化块
- 构造函数在创建对象时执行
- package explore.testEntity;
-
- public class testClass {
-
- private String phone = a();
- private static String phone1 = a();
-
- static {
- System.out.println("static执行");
- }
- public static String a(){
- System.out.println("调用static方法a");
- return "调用static方法a";
- }
- public testClass(){
- System.out.println("构造函数");
- }
- {
- System.out.println("非静态内容");
- }
-
-
- public static void main(String[] args) {
- testClass tc = new testClass();
-
- }
- }

- package explore.testEntity;
-
- public class testClass {
-
- private static int k = 1;
- private static testClass t1 = new testClass("t1");
- private static testClass t2 = new testClass("t2");
- private static int i = print("i");
- private static int n = 99;
-
- {
- print("初始化块");
- }
-
- public testClass(String str) {
- System.out.println((k++) + ":" + str + " i=" + i + " n=" + n);
- ++i;
- ++n;
- }
-
- static {
- print("静态块");
- n = 100;
- }
-
- private int j = print("j");
-
- public static int print(String str) {
- System.out.println((k++) + ":" + str + " i=" + i + " n=" + n);
- ++n;
- return ++i;
- }
-
- public static void main(String[] args) {
- testClass tc = new testClass("explore.testClass.test");
-
- }
- }
