java类初始化顺序-阿里笔试题


阿里笔试题之写出程序输出结果:

package com.patrick.bishi;

public class TestVar {
	public static int k = 0;
	public static TestVar t1 = new TestVar("t1");
	public static TestVar t2 = new TestVar("t2");
	public static int i = print("i");
	public static int n = 99;
	public int j = print("j");
	{
		print("构造");
	}
	static {
		print("静态");
	}

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

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

	public static void main(String[] args) {
		TestVar t = new TestVar("init");
	}
}
结果:

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

分析:

        初始化一个类(main方法执行之前),主要是对静态成员变量的初始化,过程分为两步:1)按照静态成员变量的定义顺序在类内部声明成员变量;2)按类中成员变量的初始化顺序初始化。

        本例中,先声明成员变量k,t1,t2,i,n,此时,k=i=n=0;t1=t2=null,然后按顺序初始化这几个成员变量,k复制0,t1初始化,执行构造函数,构造函数执行需要先对对象的成员属性先进行初始化,因此执行 j 的初始化,再执行对象的代码块,再是构造函数本身,同理t2初始化,接下来再是 i 和  n 的初始化,然后到main方法中的对象 t 的初始化,对象的初始化同理t1的初始化。

参考http://www.cnblogs.com/lmtoo/archive/2012/04/08/2437918.html,得到此例转换成class的类似代码:

package com.patrick.bishi;

public class TestVarClass {

	public static int k = 0;
	public static TestVarClass t1 = null;
	public static TestVarClass t2 = null;
	public static int i = 0;
	public static int n = 0;
	static {
		k = 0;
		t1 = new TestVarClass("t1");
		t2 = new TestVarClass("t2");
		i = print("i");
		n = 99;
		print("静态");
	}

	int j = 0;

	public TestVarClass(String str) {
		j = 0;
		{
			j = print("j");
			print("构造");
		}
		System.out.println((++k) + ":" + str + "	i=" + i + "	n=" + n);
		++i;
		++n;
	}

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

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

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值