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!
Inheritance is used to define a
is-arelationship. A SavingsAccount is an Account, and a CreditAccount is an Account. So, since aList<Account>is used to containAccounts, and a CreditAccount or SavingsAccount is an Account, you can add instances of both classes into theList<Account>: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.