[英]Java constructor confusion, what goes where?
我不確定應該將哪些內容放置在構造函數中以及什么應該是字段,所以我注意到您可以添加要初始化的內容,而不必將它們放入構造函數中。 這是兩個示例,我不確定哪個最好使用以及其背后的原因。
范例1:
public class PurchaseOrder {
private String date;
private String customerID;
private String productCode;
private int quantity;
private int discountRate;
private int pricePerUnit;
private CustomerDetails customer; // The part that I'm changing
public PurchaseOrder(OrderDate date, String id,
Product product, int quantity) {
this.discountRate = customer.getDiscountRate();
this.date = date.getDate();
this.customerID = customer.getCustomerID();
this.productCode = product.getProductCode();
this.quantity = quantity;
this.pricePerUnit = product.getPricePerUnit();
}
范例2:
public class PurchaseOrder {
private String date;
private String customerID;
private String productCode;
private int quantity;
private int discountRate;
private int pricePerUnit;
public PurchaseOrder(OrderDate date, CustomerDetails customer,
Product product, int quantity) {
this.discountRate = customer.getDiscountRate();
this.date = date.getDate();
this.customerID = customer.getCustomerID();
this.productCode = product.getProductCode();
this.quantity = quantity;
this.pricePerUnit = product.getPricePerUnit();
}
請注意,我可以將CustomerDetails客戶放入構造函數中,也可以將其作為變量。 如果在構造函數中,則意味着如果一個對象由此類構成,則它還必須包含CustomerDetails的信息。 但是兩者都很好。 最佳選擇是什么,原因是什么?
您在構造函數中作為參數傳遞的內容已經在另一個類中作為對象進行了處理,例如
CustomerDetails customerInConstructor = new CustomerDetails();
那你可以走了
PurchaseOrder purchase = new PurchaseOrder(customerInConstructor, otherParameters)
如果您不想傳入由上一個類創建的對象,而是為另一個類創建一個新對象,則可以像第一個示例中所示為它創建一個變量。
private CustomerDetails customer;
構造函數主要是從諸如您的主類之類的其他類中獲取變量,並使用這些變量來生成影響它們或向其中添加內容的方法的方法。 希望我能有所幫助,祝您有美好的一天!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.