Java继承构造执行顺序

 

package test;

public class Father {
	static{
		System.out.println("I am Father");
	}

	public Father() {
		super();
		System.out.println("Father Create");
	}
	

}

 

package test;

public class Son extends Father{
	
	static{
		System.out.println("I am Son");
	}

	public Son() {
		super();
		System.out.println("Son Create");
	}
	
	public Son(int s) {
		super();
		System.out.println("Son Create with param: int");
	}
	
	public static void main(String[] args) {
		Son s = new Son();
	}

}

 

 

package test;

public class GrandChild extends Son {
	
	static{
		System.out.println("I am GrandChild");
	}
	
	


	public GrandChild() {
		super();
		System.out.println("GrandChild Create");
	}




	public GrandChild(int s) {
		super(s);
		System.out.println("GrandChild Create with param: int");
	}

	public GrandChild(long s) {
		this((int)s);
		System.out.println("GrandChild Create with param: long");
	}


	public static void main(String[] args) {
		GrandChild gc = new GrandChild(3l);

	}

}

 

 

运行以下代码

	public static void main(String[] args) {
		GrandChild gc = new GrandChild();

	}

 结果为:

I am Father
I am Son
I am GrandChild
Father Create
Son Create
GrandChild Create

 运行以下代码

	public static void main(String[] args) {
		GrandChild gc = new GrandChild(3);

	}

 结果为

I am Father
I am Son
I am GrandChild
Father Create
Son Create with param: int
GrandChild Create with param: int

 运行以下代码

	public static void main(String[] args) {
		GrandChild gc = new GrandChild(3L);

	}

 结果为:

I am Father
I am Son
I am GrandChild
Father Create
Son Create with param: int
GrandChild Create with param: int
GrandChild Create with param: long

 

以上:

 

1 类中的静态对象先于static{}执行

2  static{}中的代码是在构建类对象之前执行的

3 构造子类的时候是按照先父后子的顺序执行的

4 如果在子的构造函数中并没有使用显式的调用父类的构造函数(使用super),则执行无参构造函数。

5 如果使用this(),则会先调用this(),再调用下面的代码(此时父类别的默认构造函数不再执行,而会根据执行this()执行相应的父构造函数)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值