假设我有一个 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
}
现在我的问题是,我想在上面的simulate函数中找到arraylist myAccounts中类型savingAccounts和checkingAccounts的计数,我可以通过使用instanceof函数来做到这一点。但我对使用它感到困惑,因为我在很多地方都读到使用instanceof是不好的做法和代码味道,所以我如何才能将多态性融入其中以避免使用instanceof或者可以使用。此外,如果我使用 SavingAccount 的实例并在将来更改名称,我还需要在模拟功能中更新此代码!那么我应该在这里做什么呢。 谢谢
最佳答案
如果您使用 C#(您的命名约定同时表明 Java 和 C#),则可以只使用 .OfType<CheckingAccount>().Count
。
但是当然,请继续使用 instanceof
。这不是它应该谨慎使用的原因,而是当您定义子类特定的行为而不在类本身中提供实现时。
例如:
if(account instanceof CheckingAccount)
{
// Do something
} else if(account instanceof SavingsAccount) {
// Do another thing
}
相对于
account.DoAccountTypeSpecificThing();
你想做的事情是有意义的。
关于java - 在这种情况下我应该使用instanceof还是需要使用多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614919/