gpt4 book ai didi

java - 在子类中创建构造函数的最佳实践是什么

转载 作者:行者123 更新时间:2023-12-02 01:20:08 24 4
gpt4 key购买 nike

所以我正在做一个类(class)作业,我们需要创建 3 个类(class):Person、Customer 和 PreferredCustomer,其层次结构按此顺序排列。

就个人而言,我有以下构造函数:

public Person() {
this.name = "";
this.address = "";
this.phoneNumber = "";
}

public Person(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}

在客户中:

public Customer(boolean isOnMailingList, int customerId) {
this.isOnMailingList = isOnMailingList;
this.customerId = customerId;
}

在优惠客户中:

public PreferredCustomer(boolean isOnMailingList, int customerId, double purchaseAmount) {
super(isOnMailingList, customerId);
this.purchaseAmount = purchaseAmount;
this.discountPercentage = calculateDiscountPercentage();
}

所以我的问题主要涉及子类中的构造函数。我应该像在 PreferredCustomer 中那样在子类的构造函数中接受父成员,还是应该在创建对象的实例时使用 setter?我唯一担心的是子类的构造函数将具有很长的参数列表。您对此有何想法?谢谢!

最佳答案

最好在子构造函数中获取所需的所有参数,因为如果您忘记设置字段然后尝试访问它,则会面临 NullPointerException 的风险。

构造函数的职责是生成一个有效对象,该对象封装了所有其必要的数据,因此,如果您在创建时拥有该信息,那么您必须使用它,即使构造函数签名变得太长。

关于java - 在子类中创建构造函数的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com