对于银行系统,我有不同的类别。这些类是;

储蓄账户

学生账户

普通账户

现在我想创建一个ArrayList并用所有这些不同类的对象填充它,例如第一个元素是studentaccount1,第二个元素是savingsaccount2 ...,依此类推。

所以我尝试使用对象类型:

List accountList = new ArrayList<>();

但是由于这种原因,由于某种原因,我无法访问存储在类变量中的值,例如:

accountList.add(saving1);

accountList.get(saving1)不会显示在这些类中声明的方法。

那么,如何解决此问题,或以其他方式实现它呢?

编辑:

我忘了提到普通帐户是父类,而StudentAccount和SavingsAccount都是子类。

因此,我意识到我可以直接将ArrayList声明为NormalAccount类型(父类类型),并实现我想要的。

这些类中的类层次结构是什么?

您是否有针对三个帐户类别的父类别?

stackoverflow.com/questions/20295671/

NormalAccount是父类,Student和Savings都是从NormalAccount继承的子类

您可以在这些对象之间创建层次结构,似乎BankAccount类可以充当您在此处拥有的这些类的父类。 然后,您可以将基本方法添加到父级,并将帐户特定的方法添加到子级。 那么list将是:List list = new ArrayList <>(); 收到后,您需要检查哪个实例是什么。

使用通用方法创建接口Account,并让所有这些帐户实现该接口。

public class SavingsAccount implements Account { ... }

然后创建实现此接口的类型的列表。

List accountList = new ArrayList<>();

我不建议您仅为此目的创建标记界面。这是一个坏主意。接口应具有公共方法。

另外,Account本身可以是一个(抽象的)类,这些特定的内容将从该类扩展出来-在此处包括避免代码重复的通用功能。这取决于您要实现的目标到底是什么,以及哪个适合您的设计。

编辑:

您错过了向我们透露一个非常重要的事实,即NormalAccount是其他父母的父母。因此,解决方案非常简单:

List accountList = new ArrayList<>();

使用Object类时,在数据检索期间,需要转换检索到的数据才能使用这些方法。尝试这样的事情:

(SavingsAccount) accountList.get(saving1)

您将能够访问方法

这不是未来的好方法。

您无法访问类的方法。相反,您只能在示例中访问Object类的方法。

我认为您可以将通用方法声明放在接口或抽象类中,然后实现它们。

I forgot to mention that Normal account is the parent class and both

"StudentAccount" and"SavingsAccount" are subclasses.

So can I just declare the ArrayList as a"NormalAccount" type and then

be able to access the variables?

对,就是这样。您可以这样定义它,

List accountList = new ArrayList<>();

您的班级带有后缀_Account,所以我想它们具有相似的字段。

为它们创建一个超类,接口或类:

public class Account {
}
public class StudentAccount extends Account {
}

然后将您的列表声明为:

List accountList = new ArrayList<>();
Account normal = new NormalAccount();
accountList.add(normal);