Java在实例化一个对象的时候,如果没有显式使用super(),则会先调用父类的无参构造函数(不是和自己构造函数参数数量对应的那个),然后调用子类的构造函数,如果父类不是Object类,则一直向上追溯到Object类为止,super()只能在构造函数的第一行使用,在别的地方使用均为非法,一般情况下构造函数不用写super(),但是如果一个类有多个构造函数的时候,为了便于理解,往往要显式调用super()。
下面示例代码的运行结果为:
I am father
I am son:baidu
I am father
I am son
示例代码:
下面示例代码的运行结果为:
I am father
I am son:baidu
I am father
I am son
示例代码:
1. public class Test {
2. public static void main(String[] args) {
3. new Son("baidu");
4. new Son();
5. }
6. }
7.
8. class Farther{
9. public Farther(){
10. System.out.println("I am father");
11. }
12.
13. public Farther(String name){
14. System.out.println("I am father:"+name);
15. }
16. }
17.
18. class Son extends Farther{
19. public Son(){
20. System.out.println("I am son");
21. }
22. public Son(String name){
23. //super("google");
24. System.out.println("I am son:"+name);
25. }
26. }
2. public static void main(String[] args) {
3. new Son("baidu");
4. new Son();
5. }
6. }
7.
8. class Farther{
9. public Farther(){
10. System.out.println("I am father");
11. }
12.
13. public Farther(String name){
14. System.out.println("I am father:"+name);
15. }
16. }
17.
18. class Son extends Farther{
19. public Son(){
20. System.out.println("I am son");
21. }
22. public Son(String name){
23. //super("google");
24. System.out.println("I am son:"+name);
25. }
26. }