Java 继承中的初始化循序

先看测试代码:

/**
 * 
 */

/**
 * @author GBD_PC
 *
 */
public class InheritInitTest {
	
	public static void main(String[] args)
	{
		Super superTest = new Super();
	}
}

class Base
{
	
	static String sMsg = InitTestString("Base");
	
	static {
		System.out.println("static block of Base");
	}
	
	private TestMember testMember = new TestMember("Base");
	
	static StaticMember member = new StaticMember("Base");
	
	Base()
	{
		System.out.println("Base construct");
	}
	
	static String InitTestString(String msg)
	{
		System.out.println("static local memeber of " + msg);
		return msg;
	}
}

class Super extends Base
{
	static String sSuperMsg = Base.InitTestString("super");
	
	static {
		System.out.println("static block of Super");
	}
	
	static StaticMember member = new StaticMember("Super");
	
	private TestMember testMember = new TestMember("Super");
	
	Super()
	{
		System.out.println("Super construct");
	}
	
	
}

class StaticMember
{
	static String sMemeberMsg = Base.InitTestString("Static Member");
	
	static {
		System.out.println("Static Member static block");
	}
	
	
	
	private String msg;
	
	StaticMember(String msg)
	{
		System.out.println("Static Member construct of " + msg);
		this.msg = msg;
	}
	
	private TestMember testMember = new TestMember("no static member in the static memeber of " + msg);
	
}

class TestMember
{
	TestMember(String msg)
	{
		System.out.println("no static member construct in " + msg);
	}
}

运行结果:

static local memeber of Base
static block of Base
static local memeber of Static Member
Static Member static block
no static member construct in no static member in the static memeber of null
Static Member construct of Base
static local memeber of super
static block of Super
no static member construct in no static member in the static memeber of null
Static Member construct of Super
no static member construct in Base
Base construct
no static member construct in Super
Super construct

根据以上结果,结论为:

单个类中:

1. 先初始化静态成员(包括静态块), 按照定时顺序

2. 再初始化成员变量

3.构造函数

继承组合类中:

1.  先基类静态成员

2. 静态成员中还有静态成员,则递归初始化。

3. 静态成员的非静态变量

4. 静态成员构造函数

5. 派生类静态成员(递归1~4)

6. 基类非静态成员

7. 基类构造函数

8.派生类非静态成员

9.派生类构造函数


总结: 总之原则就是

1. 先静态成员,然后非静态成员初始化,然后构造函数。

2.递归顺序为,先成员变量,再到派生类。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值