java-编辑父项列表中的子项
我有一个名为customer的抽象类和另一个名为payCust的类,它扩展了这个抽象类。还有另一个客户机类用于初始化客户列表。java-编辑父项列表中的子项,java,list,arraylist,extends,Java,List,Arraylist,Extends,我有一个名为customer的抽象类和另一个名为payCust的类,它扩展了这个抽象类。还有另一个客户机类用于初始化客户列表。list custList=new ArrayList() customer类有一个构造函数,如下所示: public Customer(String name, String email, String mag) { this.CusEmail = email; this.CusName = name; this.maga
list 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?
注意:电子邮件对每个客户来说都是独一无二的您必须将其转换为付费客户
(假设您知道它是付费客户
):
您必须在ArrayList中检查对象的实例类型,并强制转换它以供使用
例如,类似这样的事情:
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}
如果列表中有多个子类Customer,这是更好的答案。
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}