2014-12-22 17 views
0

我是一名新程序員,我想知道何時使用重載構造函數的最佳實踐以及與單主構造函數不同的原因。Java中的構造函數重載 - 何時使用它?

+2

購買Josh Bloch的Effective Java。在這方面有很多優秀的建議,但是在這裏總結一個答案是太長了。 –

+0

你也可以看看這裏http://stackoverflow.com/questions/18444198/advantages-of-constructor-overloading – Vihar

+0

從下面的答案我已經學會了最好的使用它 –

回答

3

簡短的回答是:您應該在需要時使用重載。

作爲一個活生生的例子,來看看選擇JLabel API:https://docs.oracle.com/javase/8/docs/api/javax/swing/JLabel.html

的JLabel有相當多的構造函數:一個只需要一個字符串,即需要一個字符串和圖標,一個只有有一個圖標,一個根本沒有任何爭論。

當你想要構造那種JLabel時,你會使用每個構造函數:一個顯示一個String,一個顯示一個String和一個圖標,一個只顯示一個圖標,或者一個不顯示任何東西(直到你調用其setter函數之一)。

new Student(45); // given student id 
    new Student("name"); // given student name 
    new Student(45,"name"); // given student registration id and name 

這有助於緩解:當你想允許用戶創建多個不同的ways.For例如對象能夠在以下不同的方法來創建一個簡單的學生類對象

0

構造函數重載是有用根據我們的要求創建對象的任務。你可以將這個概念與各種java API聯繫起來,因爲它提供了許多不同的方式來初始化一個類的對象。

您也可以將Construstor Overloading與構造函數鏈結合使用。 這裏是一個examlple:

public Student (int id){ 
    this(id,"ANY-DEFAULT-NAME"); // calls the constructor of same class with 2 params 
} 

public Student (String name){ 
    this(ANY-DEFAULT-ID,name);// calls the constructor of same class with 2 params 
} 

public Student (int id,String name){ 
    // here you can initialize the instance variables of the class. 
} 
0

可以重載基於在您需要的構造函數。例如,假設您有一個名爲Dog的簡單類,它具有一些屬性,如:名稱,品種,生日,所有者和膚色。

public class Dog { 

    private String name; 
    private String breed; 
    private Date birthday; 
    private String owner; 
    private String skinColor; 

    /*Getters and Setters*/ 
    ... 
} 

如果實例類型狗的對象,並要設置全部或部分屬性的值,你就必須調用該對象的所有制定者的方法,但與構造,就可以保存該步驟直接在實例對象的每個時刻傳遞值。

例子:

public class Dog { 

    private String name; 
    private String breed; 
    private Date birthday; 
    private String owner; 
    private String skinColor; 

    public Dog(String name, String breed,Date birthday,String owner,String skinColor){ 
    this.name = name; 
    this.breed = breed; 
    this.birthday = birthday; 
    this.owner = owner; 
    this.skinColor = skinColor; 
    } 

    /*Getters and Setters*/ 
    ... 
} 



Dog myDog = new Dog("Jose", "Chiguagua",new Date(),"Jhon","Brown"); 

如果你想唯一實例,只有名稱的對象,你也一樣可以做到。一個好的做法是,如果你有一個具有必要的屬性的對象來填充某個點,那麼提供默認的構造函數,如果你沒有提供它,你將總是需要傳遞一些對象的值。這爲程序員提供了靈活性。