Home » Java » How do I create an ArrayList filled with different types of objects?

How do I create an ArrayList filled with different types of objects?

Posted by: admin October 29, 2018 Leave a comment

Questions:

I have different classes for a bank system. These classes are;

  • SavingsAccount
  • StudentAccoun
  • NormalAccount

Now I want to create an arraylist and populate it with objects of all these different classes, e.g. first element being studentaccount1, second element being, savingsaccount 2… and so on.

So I tried using the object type:

List<Object> accountList = new ArrayList<>();

But with this approach, for some reason I’m unable to access the values stored in the class variables, for example:

accountList.add(saving1);

accountList.get(saving1) doesn’t bring up the methods declared in those classes.

So how could I fix this, or implement it in some kind of another way?

EDIT:

I forgot to mention that Normal account is the parent class and both StudentAccount and SavingsAccount are subclasses.

Therefore I realized that I can just declare the ArrayList as the NormalAccount type (parent class type) instead and achieve what I wanted.

Answers: