Java 用于打印客户对象的数组列表
如何使用Customer类型的数组列表(它有两个子类,nonmember和member)通过比较打印出所有Customer对象?换句话说,我想检查某个索引处的数组列表,检查它是非成员对象还是成员对象,并相应地打印输出。这是我的密码:Java 用于打印客户对象的数组列表,java,arraylist,Java,Arraylist,如何使用Customer类型的数组列表(它有两个子类,nonmember和member)通过比较打印出所有Customer对象?换句话说,我想检查某个索引处的数组列表,检查它是非成员对象还是成员对象,并相应地打印输出。这是我的密码: ArrayList<Customer> customerList = new ArrayList<Customer>(); for(int i = 0; i < customerList.size(); i++) { if(c
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.
}
}
使用
Customer
作为参数化类型声明arraylist:
// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();
课程:(例如)
非常感谢您的洞察力。我会试试这个。
public String toString()
{
return "NonMember Customer:" + super.toString() +
"Visit Fee:\t\t" + visitFee + "\n\n";
}
// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();
for(int i =0; i < customerList.size();i++) {
// Implicit call to the toString() method
System.out.println(customerList.get(i));
}
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 !");
}
}