我有2个子类(MultiCard和BasicCard),我想从Bank类调用属于MultiCard的方法(addCurrency)。该方法用于在具有货币ArrayList的MultiCard内添加更多货币。但是,由于MultiCard是Card类的子类,因此无法访问MultiCard。所有卡都存储在List<Card>cards中;

我不想使用基于转换的解决方案(先检查instanceof然后将Card实例转换为MultiCard
超级班:

public abstract class Card implements Comparable<Card>, Cloneable
{
protected String id;
protected String name;
protected List<Purchase> purchases;
static int counter = 1000;

public Card(String name)
{
    counter++;
    this.id = Integer.toString(counter);
    this.name = name;
    this.purchases = new ArrayList<Purchase>();
}


我想在类MultiCard中使用的方法扩展了Card

public class MultiCard extends Card implements Cloneable
{
protected static List<String> currencies;
protected double[] balance;
public static final int currencyCount = 5;
public MultiCard (String name)
{
    super (name);
    currencies = new ArrayList<String>();
    balance = new double[currencyCount];
    currencies.add ("AUD");
    for (int i = 0; i < balance.length; i++)
        balance[i] = 0;
}
public boolean addCurrency (String currency)
{
    if (currencies.size () == currencyCount ||containsCurrency (currency)) {
        return false;
    }
    currencies.add (currency);
    return true;
}


我需要在班级类Bank中修改的方法addCurrency()

private static final String[] currencyLabel = { "AUD", "NZD", "USD", "CND", "YEN", "BPD" };
private static final double[] currencyRate = { 1.0, 1.2, 0.75, 0.85, 80, 0.7 };
private String adminUsername;
private String adminPassword;

Map<String, User> users = new HashMap<>();// username

public Bank(String admName, String admPassword){
    this.adminUsername  = admName;
    this.adminPassword = admPassword;
public boolean addCurrency(String cardID, String username, String password, String currency) { ...
}


方法addCurrency用于在MultiCard中的列表内添加货币。它调用MultiCard中的方法

这是我尝试的:

public boolean addCurrency(String cardID, String username, String password, String currency)
{
   User user = users.get(username);
   user.getACard(cardID, username, password); // here is my problem - a Card instance is returned, which must be cast to a MultiCard

}

最佳答案

由于问题有点令人困惑,因此我假设您在调用user.getACard(cardID, username, password)方法时,会得到Card的对象。理想的解决方法是调用addCurency()方法,
您可以在Card类中添加抽象方法public boolean addCurrency (String currency)(如果允许,则可以修改Card类)。
否则,您必须将Card对象转换为MultiCard对象。

09-30 00:37