Java构造函数 -- 为什么子类有时需要在构造函数中调用super呢?

Java在实例化一个对象的时候,如果没有显式使用super(),则会先调用父类的无参构造函数(不是和自己构造函数参数数量对应的那个),然后调用子类的构造函数,如果父类不是Object类,则一直向上追溯到Object类为止,super()只能在构造函数的第一行使用,在别的地方使用均为非法,一般情况下构造函数不用写super(),但是如果一个类有多个构造函数的时候,为了便于理解,往往要显式调用super()。

下面示例代码的运行结果为:
I am father
I am son:baidu
I am father
I am son

示例代码:

 

   1public class Test {  
   
2.     public static void main(String[] args) {  
   
3.         new Son("baidu");  
   
4.         new Son();  
   
5.     }  
   
6. }  
   
7.   
   
8class 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.   
  
18class 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. } 

 

 

posted @ 2011-01-03 12:25  super119  阅读(1020)  评论(0编辑  收藏  举报