1+ /**
2+ * Sample project to explain the abstraction.
3+ * The abstract sub classes can decide on overriding.
4+ * If an abstract class overrides any abstract methods of their super class,
5+ * upcomping sub classes do not need to override those methods.
6+ *
7+ * @author L.Gobinath
8+ */
9+ public class BankAccountDemo {
10+ public static void main (String [] args ) {
11+ doStuff (new ChildrensSavingsAccount ());
12+ doStuff (new GeneralSavingsAccount ());
13+ doStuff (new CurrentAccount ());
14+ }
15+
16+ public static void doStuff (Account acc ) {
17+ System .out .println ("Account name: " + acc .getName ());
18+ System .out .println ("Is cheque available: " + acc .isChequeAvailable ());
19+ acc .interest ();
20+ }
21+ }
22+
23+ /**
24+ * Abstract class Account with two abstract methods.
25+ */
26+ abstract class Account {
27+ /**
28+ * Abstract method.
29+ */
30+ public abstract void interest ();
31+
32+ /**
33+ * Abstract method.
34+ */
35+ public abstract boolean isChequeAvailable ();
36+
37+ /**
38+ * Non-abstract method.
39+ * An abstract class can have any number of non-abstract methods.
40+ * @return The name of the account
41+ */
42+ public String getName () {
43+ String accName = this .getClass ().toString ().replace ("class " , "" );
44+ return accName ;
45+ }
46+ }
47+
48+ /**
49+ * Abstract sub class of Account.
50+ * Overrides only one abstract method: isChequeAvailable.
51+ * Sub classes do not need to override isChequeAvailable.
52+ */
53+ abstract class SavingsAccount extends Account {
54+ @ Override
55+ public boolean isChequeAvailable () {
56+ return false ;
57+ }
58+ }
59+
60+ /**
61+ * Non-abstract sub class of SavingsAccount.
62+ * No need to override isChequeAvailable.
63+ * Must override the abstract method interest.
64+ */
65+ class ChildrensSavingsAccount extends SavingsAccount {
66+ @ Override
67+ public void interest () {
68+ System .out .println ("Interest: 5.0%" );
69+ }
70+ }
71+
72+ /**
73+ * Non-abstract sub class of SavingsAccount.
74+ * No need to override isChequeAvailable.
75+ * Must override the abstract method interest.
76+ */
77+ class GeneralSavingsAccount extends SavingsAccount {
78+ @ Override
79+ public void interest () {
80+ System .out .println ("Interest: 4.0%" );
81+ }
82+ }
83+
84+ /**
85+ * Non-abstract sub class of Account.
86+ * It must override both interest and isChequeAvailable.
87+ */
88+ class CurrentAccount extends Account {
89+ @ Override
90+ public void interest () {
91+ System .out .println ("No interest" );
92+ }
93+
94+ @ Override
95+ public boolean isChequeAvailable () {
96+ return true ;
97+ }
98+ }
0 commit comments