Reputation: 9319
I'm learning Java and I have a problem that I can't understand or solve! I have just learned about inheritance and abstract methods. So I have done a superclass that I call Account and then two subclasses that I call savingsAccount and creditAccount. I have also put the objects of the subclasses into two separate arraylist.
But now I have to change it, because my teacher want me to create an account object and put that into an arraylist and reach the savingsAccount objects and the creditAccount objects from that list instead of having two separate list.
But when I'm reading about absract classes and methods, it seems that you can't create an object of an abstract superclass!? So how should I create an object of account and still use the abstract methods? Help is appreciated! Thanks!
Upvotes: 2
Views: 2547
Reputation: 692281
Inheritance is used to define a is-a
relationship. A SavingsAccount is an Account, and a CreditAccount is an Account. So, since a List<Account>
is used to contain Account
s, and a CreditAccount or SavingsAccount is an Account, you can add instances of both classes into the List<Account>
:
Account a = new CreditAccount();
list.add(a);
When you'll get an account from the list (Account a = list.get(0)
for example), this account will be either a CreditAccount or a SavingsAccount, and calling an abstract method will call the implementation of the method defined in the subclass.
Upvotes: 4
Reputation: 19443
List<Account> accountList = new ArrayList<Account>();
Will work even if Account
is abstract.
Upvotes: 2
Reputation: 9293
try
List<Account> accounts = new ArrayList<Account> ();
it will work - you can add both of your subclasses here, but can't add Account object - as they are absract and cannot be created
Upvotes: 2