【发布时间】:2016-02-26 02:55:51
【问题描述】:
我有这几行代码:
public String getAccountType(BankAccount a){
if(a instanceof RegularAccount)
return "RA";
else if(a instanceof SavingsAccount)
return "SA";
else if(a instanceof cityAccount)
return "CLA";
else if(a instanceof StateLawAccount)
return "SLA";
else if(a instanceof FederationLawAccount)
return "FLA";
else
return null;
}
BankAccount 是下面所有类的超类(抽象)。在这个方法中,我只想返回一个字符串中的“a”类。
但是,我想知道除了这堆if/else 语句之外,是否有更好的方法来验证“a”类。有吗?我可以用 switch 语句来做吗?如果有,怎么做?
【问题讨论】:
-
知道是哪个类的目的是什么?
-
使用 OOP 并在您的每个 Account 类中定义
getAccountType -
签出this
标签: java if-statement abstract superclass instanceof