Repository navigation
Expand file tree
/
Copy pathPolymorphismDemo.java
More file actions
38 lines (34 loc) · 1.7 KB
/
Copy pathPolymorphismDemo.java
File metadata and controls
38 lines (34 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.time.LocalDate;
/**
* The PolymorphismDemo class is a tester that puts different account types in one Account array
* and calls the same methods on each. Each object responds with its own class's version of the method.
* It does not write to any files.
*/
public class PolymorphismDemo {
public static void main(String[] args) {
Account[] accounts = {
new Account("BaseExample", 90000001, 500.0),
new NewAccount("NewExample", LocalDate.of(2000, 1, 1), 500.0),
new DemoAccess("AccessExample", 90000003, 500.0),
new DemoSavings("SavingsExample", 90000004, 500.0)
};
for (Account account : accounts) {
System.out.println(account);
account.deposit(100); // same call, each class's own version runs
System.out.println(" after deposit 100: " + account.getBalance());
account.withdraw(550);
System.out.println(" after withdraw 550: " + account.getBalance());
System.out.println();
}
}
/** AccessAccount that skips the file log, so the demo doesn't touch balanceSheet.txt. */
private static class DemoAccess extends AccessAccount {
DemoAccess(String name, int number, double balance) { super(name, number, balance); }
@Override protected void recordTransaction(String type, double amount) { }
}
/** SavingsAccount that skips the file log, so the demo doesn't touch balanceSheet.txt. */
private static class DemoSavings extends SavingsAccount {
DemoSavings(String name, int number, double balance) { super(name, number, balance); }
@Override protected void recordTransaction(String type, double amount) { }
}
}