【问题标题】:java - Editing child in list of parentsjava - 在父母列表中编辑孩子
【发布时间】:2014-05-19 02:21:06
【问题描述】:

我有一个名为 customer 的抽象类和另一个名为 payCust 的类,它扩展了这个抽象类。还有一个初始化客户列表的客户端类。List<Customer> custList = new ArrayList<>();

客户类有如下构造函数:

public Customer(String name, String email, String mag) {
        this.CusEmail = email;
        this.CusName = name;
        this.magazine = mag;
    }

payCust 有以下构造函数:

public PayCust(String _name, String _email, String _accountType, String _custMag) {
        super(_name, _email, _custMag);
        this.accountType = _accountType;
    }

所有变量都有公共的 get 和 set 方法。例如

public void setName(String name) {
            this.CusName = name;
        }
public String getName() {
        return this.CusName;
    }

我的问题是,如果 custList 添加了 PayCust。如何从该列表中编辑客户的 accountType? 注意:电子邮件对每个客户都是独一无二的

【问题讨论】:

    标签: java list arraylist extends


    【解决方案1】:

    您必须检查 ArrayList 中对象的实例类型并将其强制转换以供使用。

    类似这样的东西,例如:

    for (Customer c : custList){
        if(c instanceof PayCust){
            PayCust pc = (PayCust) c;
            pc.getAccountType();
        }
    }
    

    【讨论】:

    • 如果列表中有多个 Customer 子类,这是更好的答案。
    【解决方案2】:

    您必须将其转换为 PayCust(假设您知道它是 PayCust):

    PayCust example = (PayCust) custList.get(0);
    String accountType = example.getAccountType ();
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2011-09-24
      • 1970-01-01
      • 2017-09-08
      相关资源
      最近更新 更多