CSE143 Inheritance Examples handout #27 We developed the following class in lecture on Monday: import java.awt.*; public class MyPoint extends Point { private int count; public MyPoint() { this(0, 0); } public MyPoint(int x, int y) { super(x, y); } public void translate(int dx, int dy) { count++; super.translate(dx, dy); } public int getTranslateCount() { return count; } } It is a variation of the Point class that keeps track of how many times it has been translated. Below is a sample inheritance question. 1. Programming with inheritance. A cash processing company has developed a Java class called Account that can be used to process transactions. It has many methods including the following: public Account(Client c) // the only constructor for an Account, takes as a parameter a // a reference to a Client object that stores start-up information public boolean process(Transaction t) // processes the next transaction, returning true if the transaction // was approved and returning false otherwise The Transaction class also has many methods including: public int value() // returns the value of this transaction in pennies (could be // negative, positive or zero) Assume that all transactions enter the system by a call on the process method described above. The company wishes to create a slight modification to the Account class that filters out zero-valued transactions. You are to design a new class called FilteredAccount whose instances can be used in place of an Account object but which include the extra behavior of not processing transactions with a value of 0. More specifically, the new class should indicate that a zero-valued transaction was approved but shouldn't call the process method in the Account class to process it. Your class should have a single constructor that takes a parameter of type Client and it should include the following method: public double percentFiltered() // returns the percent of transactions filtered out (between 0.0 and // 100.0); returns 0.0 if no transactions of any kind have been // submitted Write your definition of class FilteredAccount below. One possible solution appears below. public class FilteredAccount extends Account { private int zeros; private int transactions; public FilteredAccount(Client c) { super(c); zeros = 0; transactions = 0; } public boolean process(Transaction t) { transactions++; if (t.value() == 0) { zeros++; return true; } else return super.process(t); } public double percentFiltered() { if (transactions == 0) return 0.0; else return zeros * 100.0/transactions; } }
Stuart Reges
Last modified: Wed Mar 1 14:06:04 PST 2006