![](/img/trans.png)
[英]if a class in its constructor contains an int,, and an array.. how can i use the array in another class.?
[英]How can I make a constructor that contains a number of the same objects but if one its empty to ignore it?
我想為包含四個填充的包裝創建一個構造函數,但是如果一個填充為空(例如只使用2或3而不是4)來執行代碼而沒有任何問題。
我目前只能使用此代碼只包含一個填充。
Wrap one=new Wrap( new Bread("Italian"), new Filling("Ham"),new Topping("Cheddar"));
使用當前的構造函數,您只能有零( null
)或一個面包,填充和頂部。
您需要重載構造函數以允許更多輸入選項。
如果您想要多個填充並且最多只有一個頂部,請添加此構造函數
Wrap(Bread b, List<Filling> fillings, Topping topping)
如果你想要有多個填充和澆頭,那么這個
Wrap(Bread b, List<Filling> fillings, List<Topping> toppings)
或者只允許最后一種情況,並使用Collections.singletonList()
來獲取一個項目的列表。
你可以使用this()
組合它們。
總結一下,這就是一個例子
Bread bread;
List<Filling> fillings;
List<Topping> toppings;
public Wrap(Bread b, List<Filling> fillings, List<Topping> toppings) {
// ...
}
public Wrap(Bread b, Filling f, Topping t) {
this(b, Collections.singletonList(f), Collections.singletonList(t));
}
public Wrap(Bread b, List<Topping> toppings) {
// Is this a pizza?
this(b, null, toppings);
}
我建議使用一個構造函數來獲取填充列表,這樣你就可以擁有一個構造函數,並強制調用者提供列表,即使它是空的。 這將允許任何數量的填充。
如果4是最大值,則調用者可以為每個未使用的參數傳入null
。
如果填充具有公共基類,則列表可以將基類作為其類型。 (或者,對象,如果你必須走得那么遠,雖然這似乎不是一個好主意。)另一種方法是使用Varargs與基類。
凌亂的方法是生成一堆構造函數,提供所有參數組合,但如果你有這么多的參數,它就會有一個糟糕的“代碼味道”。
正確的答案取決於您嘗試提供的界面以及您希望如何使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.