zoukankan      html  css  js  c++  java
  • Java类变量、实例变量的初始化顺序

    题目:

    public class InitTest{
      public static int k = 0;
      public static InitTest t1 = new InitTest("t1");
      public static InitTest t2 = new InitTest("t2");
      public static int i = print("i");
      public static int n = 99;
      
      public int j = print("j");
      {
          print("Creat");
      }
      
      static {
          print("Static");
      }
      
      public InitTest(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);
          ++n;
          return ++ i;
      }
      
      public static void main(String[] args){
    	  InitTest t = new InitTest("init");
      }
    }
    

    输出结果:

    1:j   i=0   n=0
    2:Creat   i=1   n=1
    3:t1    i=2  n=2
    4:j   i=3   n=3
    5:Creat   i=4   n=4
    6:t2    i=5  n=5
    7:i   i=6   n=6
    8:Static   i=7   n=99
    9:j   i=8   n=100
    10:Creat   i=9   n=101
    11:init    i=10  n=102

    类记载过程:加载 -> 链接(验证 -> 准备 -> 解析) -> 初始化 -> 实例化

    其中准备过程会给static成员变量赋初值,一般为0,如果是static final的话为所赋的值

    另外,实例化不一定发生在完全初始化之后,因为某些初始化伴随着实例化。

    类实例化过程:父类 构造块/实例变量->父类 构造方法 -> 子类 构造块/实例变量->子类 构造方法。

    原因在于构造方法中可能就需要使用到实例变量,因此这个时候实例变量一定要先完成初始化操作。



  • 相关阅读:
    洛谷P1421 小玉买文具
    洛谷P1035 级数求和
    洛谷 P2337 【[SCOI2012]喵星人的入侵】
    洛谷P1002 过河卒
    洛谷 P4073 [WC2013]平面图
    洛谷 P4705 玩游戏
    python3.7-初学篇-06
    python3.7-初学篇-04
    python3.7-初学篇-03
    python3.7-初学篇-02
  • 原文地址:https://www.cnblogs.com/tonyluis/p/5594979.html
Copyright © 2011-2022 走看看