/* * T04n01.java -- Demonstration of Composition (more precisely, Adaptation) * * SavingsAccount is composed of an Account object; that is, it uses * an Account object and its associated methods to do the work * needed to maintain a SavingsAccount object. */ import java.io.*; class Account { private int balance; public Account () { balance = 1; } // free money for opening an account! public Account (int initialBalance) { balance = initialBalance; } public int fetchBalance() { return balance; } public void setBalance(int newBalance) { balance = newBalance; } } class SavingsAccount { Account foundation; // Thus, a SavingsAccount object is composed // of an Account object. public SavingsAccount () { foundation = new Account(); } public SavingsAccount (int startingBalance) { foundation = new Account(startingBalance); } public int getBalance () { return foundation.fetchBalance(); } public void setBalance(int newBalance) { // foundation.balance = newBalance; // this had better fail! foundation.setBalance(newBalance); } } public class T04n01 { 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() + "."); } }