Rather than use instanceof
, which is not very object-oriented for reasons already mentioned---specifically, you should use polymorphism in an object-oriented design, you can specify the account type in your Account class and check it without using instanceof
but instead getAccountType()
.
abstract class Account
{
public enum Type { MARKET_SAVING, REGULAR_SAVING, CHECKING };
private final Type type;
private int number;
private String owner;
public Account(Type accountType, int accountNumber, String accountOwner)
{
type = accountType;
number = accountNumber;
owner = accountOwner;
}
public Type getAccountType(){ return type; }
...
}
The subclasses must be required to specify a Type
, and the compiler will enforce this if all Account constructors have a Type
parameter. With instanceof
, there is no compile-time check that all subclasses of Account
are handled. You'll have to make sure that the code handles all of the enum values, but that is often a more constrained problem than trying to know and handle all subclasses of Account because the Type
enum is specified as part of the Account data type.
Now if there is some behavior that is supposed to be different for each account, that behavior should be handled, polymorphically, within or at least through the subclasses of Account rather than through code that checks the type and performs specific operations, but if you just want to find the accounts of a particular type, having the type be a property of the Account objects will allow you to avoid depending on knowing the classes that implement each particular account type.
public class MarketSavingsAccount extends Account
{
MarketSavingsAccount(int accountNumber, String accountOwner)
{
super(Type.MARKET_SAVING, accountNumber, accountOwner);
}
...
}
Maybe there's some other implementation of MarketSavingsAccount that needs to be treated as a market savings type of account:
public class OtherMarketSavingsAccount extends Account
{
OtherMarketSavingsAccount(int accountNumber, String accountOwner)
{
super(Type.MARKET_SAVING, accountNumber, accountOwner);
}
...
}
If you have code that just want to find the market saving accounts, you would just iterate over the array and act on those of Type.MARKET_SAVING, which includes both MarketSavingsAccount and OtherMarketSavingsAccount as well as any other implementations that you may have.
for (Account account : accounts) {
if (account.getAccountType() == Type.MARKET_SAVING) {
addToDirectMailAccountsList(account); // Or whatever
}
}