java - 在父类列表中编辑child

时间:2014-04-07 01:40:03

标签: java list arraylist extends

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

customer类有一个构造函数如下:

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方法。 e.g。

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

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

2 个答案:

答案 0 :(得分:2)

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

像这样的东西,例如:

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

答案 1 :(得分:0)

您必须将其投放到PayCust(假设您知道它是PayCust):

PayCust example = (PayCust) custList.get(0);
String accountType = example.getAccountType ();
...
相关问题