Java代码执行顺序(静态变量,非静态变量,静态代码块,代码块,构造函数)加载顺序

  1 //据说这是一道阿里巴巴面试题,先以这道题为例分析下
  2 public class Text {
  3     public static int k = 0;
  4     public static Text t1 = new Text("t1");
  5     public static Text t2 = new Text("t2");
  6     public static int i = print("i");
  7     public static int n = 99;
  8     public int j = print("j");
  9 
 10     {
 11         print("构造块");
 12     }
 13     static {
 14         print("静态块");
 15     }
 16 
 17     public Text(String str) {
 18         System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);
 19         ++i;
 20         ++n;
 21     }
 22 
 23     public static int print(String str) {
 24         System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);
 25         ++n;
 26         return ++i;
 27     }
 28 
 29     public static void main(String args[]) {
 30         Text t = new Text("init");
 31     }
 32 }
 33 
 34 //执行结果
 35 1:j   i=0    n=0
 36 2:构造块   i=1    n=1
 37 3:t1   i=2    n=2
 38 4:j   i=3    n=3
 39 5:构造块   i=4    n=4
 40 6:t2   i=5    n=5
 41 7:i   i=6    n=6
 42 8:静态块   i=7    n=99
 43 9:j   i=8    n=100
 44 10:构造块   i=9    n=101
 45 11:init   i=10    n=102
 46 
 47 结果分析:
 48 实例化Text,执行顺序如下
 49 --public static int k = 0;无任何打印结果
 50 
 51 --public static Text t1 = new Text("t1");给t1赋值new Text("t1"),每次实例化对象都会依次加载非静态变量,代码块(在构造函数前面加载),构造函数,
 52 public int j = print("j");
 53 //打印1:j   i=0    n=0  此时i和n都还没赋值,初始值为0,k先自增再赋值后等于1
 54 {
 55         print("构造块");
 56     }
 57 //打印 2:构造块   i=1    n=1 第一次打印后i和n的值都为1
 58 public Text(String str) {
 59         System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);
 60         ++i;
 61         ++n;
 62     }
 63 //打印3:t1   i=2    n=2 
 64 //执行构造函数
 65 
 66 --public static Text t2 = new Text("t2");
 67 逻辑同上,实例化加载非静态变量,代码块(在构造函数前面加载),构造函数
 68 //打印4:j   i=3    n=3
 69 //打印5:构造块   i=4    n=4
 70 //打印6:t2   i=5    n=5
 71 
 72 --public static int i = print("i");
 73 //打印7:i   i=6    n=6
 74 
 75 --public static int n = 99;
 76 //n赋值为99
 77 
 78 -- static {
 79         print("静态块");
 80     }   
 81 //执行完j静态变量执行静态代码块
 82 //打印8:静态块   i=7    n=99
 83 
 84 --public int j = print("j"); //非静态变量
 85 //打印9:j   i=8    n=100
 86 
 87 --{
 88         print("构造块");
 89     }
 90 //打印10:构造块   i=9    n=101
 91 
 92 --public Text(String str) {
 93         System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);
 94         ++i;
 95         ++n;
 96     } 
 97 //最后才执行main方法里面实例化调用的构造函数
 98 //打印11:init   i=10    n=102
 99 
100 //总结:在不存在继承关系的情况下,
101 //代码执行顺序:静态变量-静态代码块-非静态变量-构造块-构造函数

存在继承关系的后面找时间在补上

原文地址:https://www.cnblogs.com/suruozhong/p/6045361.html