Unformatted text preview:

Subclassing ExampleA Template MethodDowncastingFinalType HierarchySubclassing ExampleCS 340, ReedExamples and notes taken in large part from: [http://6170.lcs.mit.edu/www-archive/Old-Fall03/lectures/handout/lec03_subclassing.pdf]Consider a Bank Account class and a class representing a transaction: class Account { String name; Vector transv; int balance; Account(String n) { transv = new Vector(); balance = 0; name = n; } boolean checkTrans(Trans t) { return (balance + t.amount >= 0); } void post(Trans t) { transv.add(t); balance += t.amount; } }class Trans { int amount; Date date; //...}Note that transactions can be checked to ensure balance > 0. Class Account can be extended by inheritance using the extends keyword: class AccountPlus extends Account { int creditLimit; AccountPlus(String n, int c) { super(n); creditLimit = c; } boolean checkTrans(Trans t) { return (balance + creditLimit + t.amount >= 0); } }Note that there is a new field creditLimit, and method checkTrans( Trans t) overrides the method of thesame name in the super class. . At runtime the system will decide which version of these two methodsto call. Account is the superclass of AccountPlus. A variable at runtime can refer to an object not of its type as long as it is a subclass.Sometimes the code clearly indicates the type of a variable:AccountPlus acc = new AccountPlus ("Zork", 100);Trans t = new Trans (100, new Date ());if (acc.checkTrans (t))acc.post (t);Here it is clear that the AccountPlus vesion of checkTrans() will be called. It is not always so clear. Consider the following:Account acc = new AccountPlus ("Zork", 100);Trans t = new Trans (100, new Date ());if (acc.checkTrans (t))acc.post (t);Note that variable acc is of type Account, but the object created is of type AccountPlus. This executes exactly as before, using the AccountPlus version of method checkTrans().Suppose we declare an array of Accounts: public static void main(String[] args) { Account [ ] accounts = new Account[3]; accounts[0] = new Account("checking"); accounts[1] = new AccountPlus("checkguard", 200); accounts[2] = new Account("savings"); // charge the monthly fee for each account for (int i = 0; i < accounts.length; i++) { Trans fee = new Trans(-1, new Date()); if (accounts[i].checkTrans(fee)) accounts[i].post(fee); }// end for }Within the for loop, the decision on which version of checkTrans() to use will be made at run-time, depending on the type of the object calling it. Array members accounts[0] and accounts[2] will use theAccount version of checkTrans(), while accounts[1] will use the AccountPlus version. This is known as polymorphism, meaning “many shapes”, since the same code can handle different types of accounts.The call to post() will always call the method within Account, though sometimes it is being called from an Account, and othertimes from AccountPlus.A Template MethodRather than making the client of the Account class validate the transaction using checkTrans() before doing the call post(), we can fold that into the post() method itself. This has the interesting effect of using polymorphism in a more round-about manner.boolean post (Trans t) {if (!checkTrans (t)) return false;transv.addElement (t);balance += t.amount;return true;}Look at the context this method sits in:class Account {boolean post (Trans t) {...}boolean checkTrans (Trans t) {...}}...class AccountPlus extends Account {boolean checkTrans (Trans t) {...}}The post() method could be called using:Account a = new AccountPlus ("Zork", 100);a.post (new Trans (-50, new Date ());System.out.println (a.balance);There is a single version of post() inside Account that is called. Inside post() the method checkTrans() is called. If the Account version gets called, the balance will stay at 0 since negative balances are not allowed. If the AccountPlus version of checkTrans() gets called, the balance will go to -50, since here negative balances within the credit limit are allowed. Polymorphism again takes over, and the AccountPlus version is called, yielding a balance of -50.This idiom is used to implement ‘frameworks’ where a collection of classes are provided that are tailored by the user by adding new subclasses. For programmers to make use of this idiom in the above example, they would have to be told to override the method checkTrans() in the subclasses. This is also known as a template, where the overall structure is provided, leaving most of the computation to methods in subclasses implemented by the programmer.DowncastingSince arrays don’t grow dynamically, we might be tempted to use a Vector instead as follows: // ********* Bad Code ********* class Bank { Vector accounts; // add accounts to Vector void chargeMonthlyFee() { for (int i = 0; i < accounts.size(); i++) { Trans fee = new Trans(-1, new Date()); if (accounts.elementAt(i).checkTrans(fee)) accounts.elementAt(i).post(fee); }// end for }// end chargeMonthlyFee }// end class BankThe Vector elementAt() method returns a generic type Object, since Vectors are used to store any Object. This means the code is attempting to use Object.checkTrans() which doesn’t exist, so the code above will be rejected by the compiler. Instead we must cast the elements as Accounts: void chargeMonthlyFee() { for (int i = 0; i { accounts.size(); i++) { Trans fee = new Trans(-1, new Date()); if (((Account) accounts.elementAt(i)).checkTrans(fee)) { ((Account) accounts.elementAt(i)).post(fee); } }//end for }and we can simplify this code by making an intermediate Account object:void chargeMonthlyFee() { for (int i = 0; i < accounts.size(); i++) { Trans fee = new Trans(-1, new Date()); Account acc = (Account) accounts.elementAt(i); if (acc.checkTrans(fee)) { acc.post(fee); } }// end for }The cast from Object to Account is called a downcast, as we are casting an object to a type further down the Object hierarchy tree. A downcast


View Full Document

UIC CS 340 - Subclassing Example

Documents in this Course
Load more
Download Subclassing Example
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Subclassing Example and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Subclassing Example 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?