/* * T04n02.java -- Demonstration of Inheritance * * Unlike T04n01, this time SavingsAccount inherits from Account, so * all of Account's methods are now also SavingsAccount's methods. * In this case, inheritance is more appropriate than composition * because a SavingsAccount "is a" variety of Account. * * Note that the main program is the same in both examples. */ import java.io.*; class Account { private int balance; public Account () { balance = 1; } public Account (int initialBalance) { balance = initialBalance; } public int fetchBalance() { return balance; } public void setBalance(int newBalance) { balance = newBalance; } } class SavingsAccount extends Account // This is Java syntax for inheritance { public SavingsAccount () { // Account's 0-argument constructor is invoked automatically } public SavingsAccount (int startingBalance) { super(startingBalance); // or: setBalance(startingBalance) } public int getBalance () { return super.fetchBalance(); // inheritance makes "super." optional //return fetchBalance(); // also works -- try it! } } public class T04n02 { 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 is now $" + nestEgg.getBalance() + "."); } }