2011-01-13 105 views
3

請不帶任何參數裏面的意思有被定義了多個參數解釋超級構造函數的Java

public class Contact { 
    private String contactId; 
    private String firstName; 
    private String lastName; 
    private String email; 
    private String phoneNumber; 

public Contact(String contactId,String firstName, String lastName, String email,  String phoneNumber) { 
    super(); //what does standalone super() define? With no args here? 
    this.firstName = firstName; 
    this.lastName = lastName;  //when is this used?, when more than one args to be entered? 
    this.email = email; 
    this.phoneNumber = phoneNumber; 
} 

超()?這是在「this.xxx」的幫助下完成的嗎?

爲什麼我們在「公共類聯繫人」本身中定義。爲什麼我們再次定義並在此提出它的論點?

+0

super在你的情況下調用父類構造函數,Object類構造函數 – ant 2011-01-13 09:55:09

回答

7

超()不帶參數裏面的意思有被定義了多個參數呢?

沒有,只是super()調用基類的無參數的構造函數,你的情況Object

它什麼也沒做。它只是在代碼中明確表示,您正在使用無參數構造函數構造基類。實際上,如果你離開了super(),它將被編譯器隱式添加回去。

那麼super()是不是暗中添加了?那麼,在某些情況下,一個類沒有無參數的構造函數。 這個類的子類必須使用例如super("hello")顯式調用某個超級構造函數。

this.lastName = lastName; //when is this used?, when more than one args to be entered?

this.lastName = lastName;無關與super()。它只是聲明構造函數參數lastName的值應該分配給成員變量lastName。這相當於

public Contact(String contactId, String firstName, String lastNameArg, 
       String email, String phoneNumber) { 
    // ... 
    lastName = lastNameArg; 
    // ... 
6

super()調用超類的默認(無參數)構造函數。這是因爲爲了構建一個對象,你必須遍歷層次結構中的所有構造函數。

super()可以省略 - 編譯器自動將其插入。

在你的情況下,超類是Object