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

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 客户放入构造函数中,或者将其作为变量。如果它在构造函数中,则意味着如果一个对象由这个 class 组成,它还必须包含 CustomerDetails 的信息。但两者都工作正常。最好的选择是什么?选择它的原因是什么?

你在构造函数中作为参数传递的内容已经在另一个class中作为对象传递,例如

CustomerDetails customerInConstructor = new CustomerDetails();

那你可以走了

PurchaseOrder purchase = new PurchaseOrder(customerInConstructor, otherParameters)

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

private CustomerDetails customer;

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