如果将对象添加到父 class arraylist,如何访问扩展函数

How to access the extended function if the object is added to the parent class arraylist

我有2个classes - CustomerPayingCustomer,其中后者是前者的延伸。

我正在尝试访问将 PayingCustomer 对象添加到父级 class - Customer 的 arrayList 的扩展方法。但是,唯一可用的方法是来自父 class 的方法,这不是我要找的方法。

有没有一种方法可以派生扩展的 class 方法,而无需进行如下所述的大量代码更改?

主要代码:

import java.util.ArrayList;

class Main {

    public static void main(String[] args)
    {
      ArrayList<Customer> cArr = new ArrayList();
      PayingCustomer c1 = new PayingCustomer ("John Doe");

      // directly accessing the extended class method with the relevant object class
      c1.setPaymentMethod("Credit"); // returns me "Credit"

      cArr.add(c1);

      System.out.println(c1.getPaymentMethod());

      //--------------------
      for (int i=0; i<cArr.size(); i++)
      {
          // Errors out, only can make use of the parent-class methods
          System.out.println(cArr.get(i).getPaymentMethod());
      }
    }
}

客户代码:

public class Customer
{
    private String name;

    public Customer(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }
}

支付客户代码

public class PayingCustomer extends Customer
{
    private String paymentMethod = "";
    
    public PayingCustomer(String name)
    {
        super(name);
    }

    public void setPaymentMethod(String methodInput)
    {
        paymentMethod = methodInput;
    }

    public String getPaymentMethod()
    {
        return paymentMethod;
    }
}

该列表接受 Customer 的实例。在迭代时,它仅将每个成员派生为 Customer 的实例。如果它是 PayingCustomer 实例,则将其转换为 PayingCustomer,然后使用它。

for (int i = 0; i < cArr.size(); i++) {
        if (cArr.get(i) instanceof PayingCustomer) {
            System.out.println(((PayingCustomer) cArr.get(i)).getPaymentMethod());
        } else {
            System.out.println(cArr.get(i).getName());
        }
    }