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

10,203

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.

Share:
10,203
james
Author by

james

Computer programmer in the Midwestern United States. Most familiar with C# &amp; Javascript.

Updated on June 04, 2022

Comments

  • james
    james almost 2 years

    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.

  • Don Roby
    Don Roby about 12 years
    You might want to give the variable a name as well.