构造器、静态代码块、普通代码块、静态变量初始化顺序 - 总结

问题引入

一直对这个问题有了解,也会涉及到类似的问题。刚好有空便测试一把,作为记录。

测试代码

新建Student与Person类,Student继承Person类。

public class Person {

    private String name;
    private Integer age;
    private Boolean sex;
    private static final String STATIC_FINAL_PARAM = getStaticFinalParam();
    private static String STATIC_PARAM = getStaticParam();

    private static String getStaticParam() {
        System.out.println("Father StaticParam");
        return "Father StaticParam";
    }

    private static String getStaticFinalParam() {
        System.out.println("Father StaticFinalParam");
        return "Father StaticFinalParam";
    }

    public Person() {
        System.out.println("Father Constructor");
    }

    static {
        System.out.println("father static code block");
    }

    {
        System.out.println("father code block");
    }

	// 省略getter、setter、toString
}
public class Student extends Person {

	private String studentNumber;
	private String School;
	private static final String STATIC_FINAL_PARAM = getStaticFinalParam();
	private static String STATIC_PARAM = getStaticParam();

	private static String getStaticParam() {
		System.out.println("Child StaticParam");
		return "Child StaticParam";
	}

	private static String getStaticFinalParam() {
		System.out.println("Child StaticFinalParam");
		return "Child StaticFinalParam";
	}

	public Student() {
		System.out.println("Child Constructor");
	}

	static {
		System.out.println("child static code block");
	}

	{
		System.out.println("child code block");
	}

	public void sayHello() {
		System.out.println("Hello,I'm chenwb!");
	}

	public static void main(String[] args) {
		Student student = new Student();
		student.sayHello();
	}
}

执行Student类的main方法:

Father StaticFinalParam
Father StaticParam
father static code block
Child StaticFinalParam
Child StaticParam
child static code block
father code block
Father Constructor
child code block
Child Constructor
Hello,I’m chenwb!

结果分析

1、首先加载父类,加载工程中先初始化static final变量,再初始化static变量,再执行静态代码块
Father StaticFinalParam
Father StaticParam
father static code block

2、然后加载子类,也是同样的顺序
Child StaticFinalParam
Child StaticParam
child static code block

3、开始对象实例化,先执行父类的普通代码块,再是构造方法
father code block
Father Constructor

4、 然后是子类普通代码块,子类构造方法
child code block
Child Constructor

5、执行后续代码
Hello,I’m chenwb!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值