Java建構函式 — 為什麼子類有時需要在建構函式中調用super呢?

來源:互聯網
上載者:User
Java在執行個體化一個對象的時候,如果沒有顯式使用super(),則會先調用父類的無參建構函式(不是和自己建構函式參數數量對應的那個),然後調用子類的建構函式,如果父類不是Object類,則一直向上追溯到Object類為止,super()只能在建構函式的第一行使用,在別的地方使用均為非法,一般情況下建構函式不用寫super(),但是如果一個類有多個建構函式的時候,為了便於理解,往往要顯式調用super()。

下面範例程式碼的運行結果為:
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. } 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.