how to initialize List in java of an abstract type so I can add sub types to the list later

abstract-class, collections, java, list

Solution

Maybe you meant:

List<BankAccount> accounts = new ArrayList<BankAccount>();

List is just an interface, you should use a concrete implementation when creating an instance, such as ArrayList for example.

Problem

tldr: how to create List of abstract type BankAccount and add concrete sub types to the list In java I have a class called BankAccount. Its an abstract class because I don't want anyone to use a regular BankAccount ever, they should be using the sub types SavingsAccount, CheckingAccount, VacationAccount. I want to have a property in a customer class that is List called accounts. In the class definition i added a property just like that and didnt initialize it to anything. In the constructor I want to add an account based on what the user specified in the constructor, however when i do this i get an error on the call to add(). It looks something like this ``` List<BankAccount> accounts; accounts.add(new CheckingAccount() ); ``` Should this work? What am I doing wrong. I tried doing ``` List<BankAccount> accounts = new List<BankAccount>(); ``` but that doesnt work.

Original source