您的位置:首页 > 编程语言 > Java开发

JAVA 继承 构造函数的执行顺序

2007-06-27 12:31 513 查看
最近看JAVA的继承关系中构造函数的执行顺序,有点晕,写了几个类验证一下,原代码如下:

package com.hf.scjp.constructor;

public class Parent1 {
public static StaticTest stat=new StaticTest(1L);
static {

System.out.println("in parent1 static code …… ");
}
public Parent1(){
System.out.println("in parent1 constructor …… ");

}
}

package com.hf.scjp.constructor;

public class Son1 extends Parent1 {
public static StaticTest stat=new StaticTest(1);
static {

System.out.println("in Son1 static code …… ");
}
public Son1(){
System.out.println("in Son1 constructor …… ");

}
public Son1(int s){
System.out.println("in Son1 constructor with param: int");

}

}

package com.hf.scjp.constructor;

public class GrandChild1 extends Son1{
public static StaticTest stat=new StaticTest();
static {

System.out.println("in GrandChild1 static code …… ");
}
public GrandChild1(){
System.out.println("in GrandChild1 constructor …… ");

}
public GrandChild1(String s){
System.out.println("in GrandChild1 constructor with param: String");

}
public GrandChild1(int s){
super(s);

System.out.println("in GrandChild1 constructor with param: int");

}
public GrandChild1(long s){
this((int)s);

System.out.println("in GrandChild1 constructor with param: long");

}
public static void main(String[] args){
GrandChild1 GrandChild1=new GrandChild1("");
System.out.println("/n/r");

GrandChild1 GrandChild2=new GrandChild1(3);

System.out.println("/n/r");
GrandChild1 GrandChild3=new GrandChild1(3L);
}
}

public class StaticTest {
public StaticTest(){
System.out.println("in StaticTest constructor param: ");

}
public StaticTest(int i){
System.out.println("in StaticTest constructor param:int ");

}
public StaticTest(long l){
System.out.println("in StaticTest constructor param:long ");

}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根

}

}

//这是一个三个类之间的继承关系继承:在孙子类中定义了main并创建三个孙子类对象,分别调用不同的构造函数,执行结果如下:
in StaticTest constructor param:long
in parent1 static code ……
in StaticTest constructor param:int
in Son1 static code ……
in StaticTest constructor param:
in GrandChild1 static code ……
in parent1 constructor ……
in Son1 constructor ……
in GrandChild1 constructor with param: String

in parent1 constructor ……
in Son1 constructor with param: int
in GrandChild1 constructor with param: int

in parent1 constructor ……
in Son1 constructor with param: int
in GrandChild1 constructor with param: int
in GrandChild1 constructor with param: long

这说明:
1 类中的静态对象先于static{}执行
2 static{}中的代码是在构建类对象之前执行的
3 构造子类的时候是按照先父后子的顺序执行的
4 如果在子的构造函数中并没有使用显式的调用父类的构造函数(使用super),则执行无参构造函数。
5 如果使用this(),则会先调用this(),再调用下面的代码(此时父类别的默认构造函数不再执行,而会根据执行this()执行相应的父构造函数)
说的自己都晕了,还是看代码来的简单容易
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: