Java构造方法链

一个关于java构造方法很有意思的东西


picture

构造方法可以调用重载的结构方法。

如果没有被显示调用,编译器就会自动地将 super() 作为构造方法的第一条语句,例如:

1
2
3
public test() {
//...
}

等价于

1
2
3
4
public test() {
super();
//...
}

一个很有意思的东西

下面代码输出什么


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
27
package test;
public class Faculty extends Employee{
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Performs Faculty's tasks");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Empoyee's over loaded constructor");
System.out.println("(3) Performs Employee's tasks");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Performs Person's tasks");
}
}

输出:

1
2
3
4
(1) Performs Person's tasks
(2) Invoke Empoyee's over loaded constructor
(3) Performs Employee's tasks
(4) Performs Faculty's tasks

理由不说辣