java子类继承加载顺序

        类的加载中包括:

  • 静态代码块
  • 代码块
  • 构造
  • 析构(c++中)

        例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class FatherTest {

private String name;
public static String nameStatic = "Tom";

FatherTest(){
System.out.println("--父类的无参构造函数--");
}

FatherTest(String name){
this.name=name;
System.out.println("--父类的有参构造函数--"+this.name);
}

static{
System.out.println("--父类的静态代码块--");
}

{
System.out.println("--父类的非静态代码块--");
}

public void speak(){
System.out.println("--父类的方法--");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SonTest extends FatherTest {

private String name;

static{
System.out.println("--子类的静态代码块--");
}

{
System.out.println("--子类的非静态代码块--");
}

SonTest(){
System.out.println("--子类的无参构造函数--");
}

SonTest(String name){
this.name=name;
System.out.println("--子类的有参构造函数--"+this.name);
}

@Override
public void speak(){
System.out.println("--子类Override了父类的方法--");
}
}
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
FatherTest father=new FatherTest("父亲的名字");
father.speak();
}
/*
* 输出:
* --父类的静态代码块--
* --父类的非静态代码块--
* --父类的有参构造函数--父亲的名字
* --父类的方法--
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
SonTest son=new SonTest("儿子的名字");
son.speak();
}
/*
* 输出:
* --父类的静态代码块--
* --子类的静态代码块--
* --父类的非静态代码块--
* --父类的无参构造函数--
* --子类的非静态代码块--
* --子类的有参构造函数--儿子的名字
* --子类Override了父类的方法--
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
FatherTest father=new SonTest("父亲的名字");
father.speak();
}
/*
* --父类的静态代码块--
* --子类的静态代码块--
* --父类的非静态代码块--
* --父类的无参构造函数--
* --子类的非静态代码块--
* --子类的有参构造函数--儿子的名字
* --子类Override了父类的方法--
*/

有种情况,子类不发生初始化。直接调用子类或父类的静态方法或者静态变量。

1
2
3
public static void main(String[] args) {
System.out.println(SonTest.nameStatic);
}