我有2个子类(MultiCard和BasicCard),我想从Bank类调用属于MultiCard的方法(addCurrency)。
该方法用于在具有ArrayList的MultiCard内添加更多货币。货币。但是,由于MultiCard是Card类的子类,因此无法访问MultiCard。所有卡都存储在--concurrent-*
中;
我不想使用基于转换的解决方案(先检查List<Card>cards
,然后将instanceof
实例转换为Card
)
超级班级:
MultiCard
我要在MultiCard类中使用的方法扩展了Card
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>();
}
我需要在Bank类中修改的方法addCurrency()
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;
}
方法addCurrency用于在MultiCard中的List内添加货币。它会在MultiCard中调用该方法
这是我尝试过的:
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) { ...
}
答案 0 :(得分:2)
由于问题有点令人困惑,我假设您在调用user.getACard(cardID, username, password)
方法时,会得到Card
的对象。理想的解决方法是调用addCurency()
方法,
您可以在Card类中添加抽象方法public boolean addCurrency (String currency)
(如果允许,则可以修改Card类)。
否则,您将必须将Card
对象转换为MultiCard
对象。