Solution: Pocket money account
Completion requirements

Class diagramm of inheritage and directed associations
1 public class PocketMoneyAccount extends Account{ 2 private Customer guardian; 3 4 PocketMoneyAccount(double amount, Customer customer, Customer guardian) { 5 super(amount, customer); // "super" causes the constructor of the superclass to be called 6 this.guardian = guardian; 7 } 8 9 public int transaction(double amount) // "Overrides" method transaction() of the superclass 10 { 11 if (balance + amount >= 0) // allowed if balance would be still >= 0 12 { 13 balance += amount; 14 return 0; // indicates OK 15 } 16 else 17 { 18 return -1; // indicates an error 19 } 20 } 21 }
Method transaction() in subclass PocketMoneyAccount overrides the method transaction() of superclass, because it has the same signature (same name and same number and data types of parameters).
An instance of superclass will use the method defined in superclass, one instance of the subclass will use that one which is defined in subclass.
super calls the corresponding method of the superclass. In line 9 this affects the constructor of the superclass.
Also remember, that for accessing to balance in subclass the access modifier has to be changed to protected in superclass:
1 public class Account { 2 ... 3 protected double balance; 4 ...
Class main remains unchanged except for the additional creation of a object of class PocketMoneyAccount (underlined):
1 import java.util.ArrayList;
2 import java.util.Arrays;
3
4 public class Main {
5
6 public static void main(String[] args) {
7 ArrayList<Customer> customers = new ArrayList<>(Arrays.asList(new Customer("Father"), new Customer("Child")));
8 ArrayList<Account> accounts = new ArrayList<>(Arrays.asList(
9 new Account(50, customers.get(0)),
10 new PocketMoneyAccount(50, customers.get(1), customers.get(0))));
11
12 for (Customer customer : customers) {
13 System.out.println("customerID=" + customer.getCustomerID() + "\tName=" + customer.getName() + ":");
14 ArrayList<Account> accountsOfCustomer = customer.getAccounts(); // navigates from customer to account
15 for (Account account : accountsOfCustomer) {
16 System.out.println("\taccount number=" + account.getAccountNumber() + "\tbalance=" + account.getBalance() + ":");
17 if (account.transaction(-100) == 0)
18 System.out.println("Transaction OK");
19 else
20 System.out.println("Transaction not allowed. Balance would be negative.");
21 }
22 }
23 }
24 }Last modified: Monday, 27 May 2019, 7:56 PM