【发布时间】:2014-10-28 17:39:49
【问题描述】:
假设我有一个 Account 类,
public class Account {
void Print();
}
我从中派生了两个子类,即 SavingsAccount 和 CheckingAccount。
public class SavingsAccount extends Account{
void Print();
}
public class CheckingAccount extends Account{
void Print();
}
现在假设我有一个驱动程序类,比如说 SimulateAccounts,它有一个 Account 类型的数组列表,
public class SimulateAccounts{
ArrayList<Node> myAccounts = new ArrayList<Node>();
void simulate()
{ //suppose some function has added added 5 savingAccounts and 10 checkingsAccounts in myAccounts arraylist
}
现在我的问题是我想在上面的模拟函数中找到arraylist myAccounts中类型savingAccounts和checkingAccounts的计数,我可以使用instanceof函数来做到这一点。但是我对使用它感到困惑,因为我在很多地方都读到使用 instanceof 是不好的做法和代码味道,所以我怎样才能将多态性融入其中以避免使用 instanceof 或者可以使用。此外,如果我使用 SavingAccount 更改的实例和未来名称,我还需要在模拟函数中更新我的此代码!那么我应该在这里做什么。 谢谢
【问题讨论】:
标签: java inheritance polymorphism instanceof