/* * T04n04.java -- Demonstration of an Abstract Class * * Continuing the modification of the Account/SavingsAccount example, * this program makes Account an abstract class and uses it as the * foundation for the SavingsAccount class. * * Account is abstract; it has two abstract methods (credit and debit). * Any class based on an abstract class must complete all abstract * methods before Java will accept it. * * Worth noting: (a) main() can ask a SavingsAccount object to use either * Account's getBalance() or SavingAccount's fetchBalance(), * thanks to inheritance. * (b) Because balance is a private instance variable of * Account, SavingAccount's methods cannot access it * directly; they must use Account's provided accessors * and mutators. */ import java.io.*; abstract class Account // note the prefix keyword 'abstract' { private int balance; public Account () { balance = 0; } // no free money any more! public Account (int initialBalance) { balance = initialBalance; } public int getBalance () { return balance; } public void setBalance(int newBalance) { balance = newBalance; } /* The two abstract method headers follow. Note that they * include the 'abstract' keyword, too, like the class does. * Also note that they end with a semicolon, and that there's * no code associated with them ... yet! */ public abstract void credit(int addition); public abstract void debit(int subtraction); } class SavingsAccount extends Account // inheriting from the abstract class { public SavingsAccount () { // Account's 0-argument constructor is invoked automatically } public SavingsAccount (int startingBalance) { super(startingBalance); // or: setBalance(startingBalance) } public int fetchBalance () { // return balance; // better not work! return getBalance(); } /* Implementations of the abstract methods. Because * SavingsAccount inherits from Account, we also inherit * the responsibility to provide implementations of Account's * abstract methods. But we still can't poke into Account's * private business! */ public void credit(int addition) { int tempBalance; // balance += addition; // better not work! tempBalance = getBalance(); tempBalance += addition; setBalance(tempBalance); } public void debit(int subtraction) { int tempBalance; // balance -= subtraction; // better not work! tempBalance = getBalance(); tempBalance -= subtraction; setBalance(tempBalance); } } public class T04n04 { public static void main (String [] args) { SavingsAccount nestEgg = new SavingsAccount(); System.out.println("Your starting balance is $" + nestEgg.getBalance() + "."); nestEgg.setBalance(5000); System.out.println("Your balance was set to $" + nestEgg.fetchBalance() + "."); nestEgg.credit(600); System.out.println("Your balance was increased to $" + nestEgg.getBalance() + "."); nestEgg.debit(400); System.out.println("Your balance was decreased to $" + nestEgg.fetchBalance() + "."); } }