JAVA对象的初始化过程

http://blog.mcuol.com/User/mcuooo/Article/497_1.htm

public class Employee {
	public static String company = "A Company";
	private String name;
	private String phone = "0571-12345678";
	
	//静态代码块
	static {
		System.out.println("static code block!");
		System.out.println("Company Name :" + company +"\n");
	}
	
	//代码块
	{
		System.out.println("code block");
		System.out.println("company phone :" + phone+"\n");
	}
	
	//默认构造函数
	public Employee(){
		this("string");
		System.out.println("Employee()"+"\n");
	}
	
	//自定义构造函数
	public Employee(String name){
		System.out.println("Employee(String)"+"\n");
		this.name = name;
	}
	
	public static void main(String args[]){
		new Employee();
	}
}


输出:
static code block!
Company Name :A Company

code block
company phone :0571-12345678

Employee(String)

Employee()




public class Manager extends Employee{

	public static String department = "Technology";
	private int salary = 5000;
	
	//静态代码块
	static {
		System.out.println("sub static code block");
		System.out.println("Manager department :" + department + "\n");
	}
	
	//代码块
	{
		System.out.println("sub code block");
		System.out.println("Manager salary :" + salary + "\n");
	}
	
	//默认构造函数
	public Manager(){
		this("string");
		System.out.println("Manager()"+"\n");
	}
	
	//自定义构造函数
	public Manager(String name){
		System.out.println("Manager(String)"+"\n");
	}
	
	public static void main(String args[]){
		new Manager();
	}
}



输出:
static code block!
Company Name :A Company

sub static code block
Manager department :Technology

code block
company phone :0571-12345678

Employee(String)

Employee()

sub code block
Manager salary :5000

Manager(String)

Manager()



小结:
1:静态变量分配内存空间并初始化
2:对象分配内存空间,并做默认初始化。
3:显示初始化并执行非静态方法块和构造函数
(在变量声明是也会为类的静态变量分配内存空间并初始化,并执行静态代码)

你可能感兴趣的:(java,Blog)