[Java]对象初始化顺序

父类:

package effectivejava;

import java.util.ArrayList;
import java.util.List;

public class Person {

	public Person()
	{
		name = "Tom";
               System.out.println("父类构造函数 name is "+name + "  "+this.toString()+"  "+ this.getClass().getName());

	}
	private String name ;
	//初始化块
	{
		name = "Jack";
		System.out.println("父类初始化块 name is "+name + "  "+this.toString());
	}
	//初始化常量数组
	private final static List<String> titles;
	static //静态区初始化
	{
		titles = new ArrayList<String>();
		titles.add("Junior");
		titles.add("Senior");
		titles.add("Expert");
		System.out.println("父类静态初始化块 titles is "+titles);
	}
	
	protected void sayHelloTo(String name)
	{
		System.out.println("父类方法 hello "+name+ "  "+this.toString());
	}
}

子类:

package effectivejava;

public class Student extends Person {

	private static final String teacher;
	public Student()
	{
		className = "Class 1A";
		System.out.println("子类构造函数 class name is "+className+ "  "+this.toString() +"  "+ this.getClass().getName());
	}
	private String className;
	{
		className = "一(2)班";
		System.out.println("子类初始化块 class name is "+className+ "  "+this.toString());
	}
	static {
		teacher = "Chinese Teacher";
		System.out.println("子类静态初始化块 teacher name is "+teacher);
	}
	
	protected void sayHelloTo(String name)
	{
		System.out.println("子类方法 say hello "+name+ "  "+this.toString());
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student o = new Student();
		o.sayHelloTo("Jack Li");
		//o = new Student();
	}
	
}

运行结果:

父类静态初始化块 titles is [Junior, Senior, Expert]
子类静态初始化块 teacher name is Chinese Teacher
父类初始化块 name is Jack  effectivejava.Student@33909752
父类构造函数 name is Tom  effectivejava.Student@33909752  effectivejava.Student
子类初始化块 class name is 一(2)班  effectivejava.Student@33909752
子类构造函数 class name is Class 1A  effectivejava.Student@33909752  effectivejava.Student
子类方法 say hello Jack Li  effectivejava.Student@33909752

结论:

1. 静态初始化块

     先父类静态初始化块
     再子类静态初始化块

2. 初始化块和构造函数

     先父类初始化块和构造函数
     再子类初始化块和构造函数

注意在父类构造函数或初始化块时的this是子类的对象地址,此时的对象类型是Student而不是Person。

你可能感兴趣的:(Java,Java)