---
title: "继承 静态 代码块 变量 构造函数等执行顺序 "
author: "lelglin"
date: "2014-02-23T13:24:28Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-02-23T13:24:28Z"
id: 2020690
url: "https://lelglin.iteye.com/blog/2020690"
---

1.静态变量和静态代码块和类绑定，类初始化时执行

 

父类的静态代码块和静态变量

子类的静态代码块和静态变量

 

父类的代码块和普通变量

父类的构造函数

 

子类的代码块和普通变量

子类的构造函数

 

 

```
public class TestExecutorOrder {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Father object = new Son();

	}

}

class P{
	public static String  print(String str){
		System.out.println(str);
		return str;
	}
}

class Father{
	static{
		System.out.println("Father Static");
	}
	
	{
		System.out.println("Father {}");

	}
	
	String i = P.print("Father Common V");
	static String s = P.print("Father Static V");
	
	public Father(){
		this.printMessage();
		i = "Father";
	}
	
	public void printMessage(){
		System.out.println(this.i);
	}
	
	
}

class Son extends Father{
	static{
		System.out.println("Son Static");
	}
	
	{
		System.out.println("Son {}");

	}
	
	String i = P.print("Son Common V");
	static String s = P.print("Son Static V");
	
	public Son(){
		this.printMessage();
		i = "Son";
	}
	
	public void printMessage(){
		System.out.println(this.i);
	}
	
	
}
```

 

 

执行结果

 

```
Father Static
Father Static V
Son Static
Son Static V
Father {}
Father Common V
null
Son {}
Son Common V
Son Common V
```

 

 

有一处需要注意

 

在调用

public Father(){

this.printMessage();

i = "Father";

 

}

此处的this.printMessage()调用的是子类

 

 

－－－－－－－－－－－－－－－－－－－－－－－－－－－

 

稍作修改

 

 

 

```
class Father{
	static{
		System.out.println("Father Static");
	}
	
	{
		System.out.println("Father {}");

	}
	
	String i = P.print("Father Common V");
	static String s = P.print("Father Static V");
	
	public Father(){
		this.printMessage();
		System.out.println(this.i);
		i = "Father";
	}
	
	public void printMessage(){
		System.out.println("Father Message");
	}
	
	
}

class Son extends Father{
	static{
		System.out.println("Son Static");
	}
	
	{
		System.out.println("Son {}");

	}
	
	String i = P.print("Son Common V");
	static String s = P.print("Son Static V");
	
	public Son(){
		this.printMessage();
		i = "Son";
	}
	
	public void printMessage(){
		System.out.println("Son Message");
	}
	
	
}
```

 结果

 

```
Father Static
Father Static V
Son Static
Son Static V
Father {}
Father Common V
Son Message
Father Common V
Son {}
Son Common V
Son Message
```