簡體   English   中英

用Java鏈接構造函數

[英]Chaining Constructors in Java

無法提出更好的標題。

一個經典的學習示例:類Human ,其中屬性是名稱,年齡,母親和父親。 父母雙方也是Human

public class Human {
    String name;
    int age;
    Human mother;
}

我想創建3個構造函數:

  1. Human() ;
  2. Human(String name, int age)
  3. Human(String name, int age, Human mother)

我確實了解鏈接的工作原理,這就是我所做的:

Human() {
    this("Jack", 22);
}

Human(int age, String name) {
    this(age, name, new Human()); // new Human() will cause SOF Error.
}

Human(int age, String name, Human mother) {
    this.age = age;
    this.name = name;
    this.mother = mother;
}

如上所述,我再次收到StackOverflowError ,我我知道為什么會發生。 公平地說,我想我會得到像人類傑克這樣的東西,而他的母親也是人類傑克

盡管如此,我不知道該怎么做。 我的猜測是,我應該使用所有參數而不是new Human()來調用構造函數,但是我不確定它是否為true以及唯一可用的選項。

將不勝感激這里的任何指導。

是的,您對它為什么會發生是正確的。 不過要確定的是:

  • new Human()稱為this("Jack", 22)
  • this("Jack", 22)稱呼this(age, name, new Human())
  • 其中的new Human() this("Jack", 22)再次調用this("Jack", 22)
  • 再次調用this(age, name, new Human())
  • 直到用完堆棧

正確的方法是確保您不會回到起點。 因此,如果在任何構造函數中使用new Human(String)new Human(String, int) ,則必須確保該構造函數( new Human(String)new Human(String, int) )也不會使用new Human(String)new Human(String, int) ,因為您將無休止地遞歸。 您需要在某個地方使用new Human(String, int, Human) 因此,例如:

Human(int age, String name) {
    this(age, name, null);
}

當然,這意味着新實例的mother將為null

如果我正確理解您的問題,則有兩個子問題:

  1. 使用Java語言 (使用構造函數)是否有其他方法?
  2. 在面向對象設計中是否有更好的方法呢?

關於第一個問題,構造函數是一個方法,您的實現產生兩個遞歸方法。 您必須中斷遞歸或引入退出條件。 還有另一種選擇-調用this(age, name, null)在第一個構造函數。

關於第二個問題,一個流行的解決方案是simple factory模式,其中只有一個帶有所有參數的私有構造函數,然后有一些公共工廠方法可以執行您想要的任何事情。

Human() {
    this.name = "Jack";
    this.age = 22;
}

Human(int age, String name) {
    this.age = age;
    this.name = name;
    this.mother = null;
}

Human(int age, String name, Human mother) {
    this.age = age;
    this.name = name;
    this.mother = mother;
}

這不會創建任何水平或嵌套構造函數

您的構造函數Human(int, String)了無條件遞歸,最終創建了StackOverflowError

構造函數重載是提供創建對象的便捷方法的一種非常常見的方法。 只要成員不是final成員並且可以在以后進行操作,則最好不要傳遞任何值(即null ),而不是動態創建更多對象。

實際上,沒有母親就沒有人,但是這可能是未知的,因此現在傳遞null將是更好的方法。

如果您需要不可變的母親 ,則必須在沒有參考的情況下提供任何構造函數,以使母親清楚可見。 即使這樣也行不通,因為您無法為人類的起源提供如此無盡的樹形結構。 通常,此類結構具有一個“根”對象,該對象沒有父對象(在此示例中為 )。

我建議不要去構造函數鏈接。 我更喜歡例如變量鏈和使用構建器設計模式以及節點類型的數據結構。

Class Human{
int age;
Sting name;
Human mother;

public  Human setAge(int age){
this.age = age;    
return this;
}

public Human setName(String name){
this.name = name;
return this;
}

public Human setHuman(Human mother){
this.mother= mother;
return this;
}

}

完成此操作后,您可以將第一個Mother實例創建為human,然后將其設置為child中的human。 讓我知道更具體的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM