Java构造函数混乱,什么去哪里?

时间:2015-03-17 00:53:34

标签: java constructor

不确定应该在构造函数中放置什么以及应该只是一个字段,我注意到你可以添加要初始化的东西,而不必将它们放在构造函数中。这里有两个例子,我只是不确定哪个最好用,以及背后的原因。

示例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的信息。但两者都很好。什么是最好的选择和原因?

1 个答案:

答案 0 :(得分:1)

作为参数在构造函数中传递的内容已在另一个类中作为对象(例如

)传递
CustomerDetails customerInConstructor = new CustomerDetails();

然后你可以去

PurchaseOrder purchase = new PurchaseOrder(customerInConstructor, otherParameters)

如果你不想传入你从前一个类创建的对象,而是为另一个类创建一个新对象,你可以为它创建一个变量,如第一个例子中所示。

private CustomerDetails customer;

构造函数主要是从其他类(如主类)中获取变量的方法,并使用这些变量来创建影响它们的方法或向它们添加内容。我希望我有所帮助,祝你有个美好的一天!

相关问题