gpt4 book ai didi

java - 用于打印客户对象的数组列表

转载 作者:行者123 更新时间:2023-11-30 07:37:27 24 4
gpt4 key购买 nike

如何使用 Customer 类型的数组列表(有 2 个子类,非成员和成员)通过比较打印出所有客户对象?换句话说,我想检查某个索引处的数组列表,并检查它是否是非成员或成员对象,并相应地打印输出。这是我的代码:

ArrayList<Customer> customerList = new ArrayList<Customer>();

for(int i = 0; i < customerList.size(); i++)
{
if(customerList.get(i) == // nonmember)
{
// want to use toString in NonMemberCustomer class
}
else // member
{
// use toString in MemberCustomer class to print output.
}
}
public String toString()    
{
return "\nMember Customer:" + super.toString() +
"Collected Points:\t" + pointsCollected + "\n\n";
}
public String toString()
{
return "NonMember Customer:" + super.toString() +
"Visit Fee:\t\t" + visitFee + "\n\n";
}

最佳答案

使用 Customer 作为参数类型声明您的数组列表:

// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();

其次,您不需要 if/else 语句来打印对象各自的 toString();只需覆盖每个类中的toString()方法& polymorphism将从那里拿走它。

for(int i =0; i < customerList.size();i++) {
// Implicit call to the toString() method
System.out.println(customerList.get(i));
}

类(class):(例如)

class Customer {
// properties & methods

@Override
public String toString() {
System.out.println("The customer's toString !");
}
}

class Member extends Customer {
// properties & methods

@Override
public String toString() {
System.out.println("The member's toString !");
}
}

class NonMember extends Customer {
// properties & methods

@Override
public String toString() {
System.out.println("The nonmember's toString !");
}
}

关于java - 用于打印客户对象的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185186/

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