ICOM 4015 Advanced Programming Lecture 12 Chapter Twelve

  • Slides: 134
Download presentation
ICOM 4015: Advanced Programming Lecture 12 Chapter Twelve: Object-Oriented Design ICOM 4015 Fall 2008

ICOM 4015: Advanced Programming Lecture 12 Chapter Twelve: Object-Oriented Design ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Chapter Twelve: Object-Oriented Design Big Java by Cay Horstmann Copyright © 2008 by John

Chapter Twelve: Object-Oriented Design Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Chapter Goals • To learn about the software life cycle • To learn how

Chapter Goals • To learn about the software life cycle • To learn how to discover new classes and methods • To understand the use of CRC cards for class discovery • To be able to identify inheritance, aggregation, and dependency relationships between classes • To master the use of UML class diagrams to describe class relationships • To learn how to use object-oriented design to build complex programs Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

The Software Life Cycle • Encompasses all activities from initial analysis until obsolescence •

The Software Life Cycle • Encompasses all activities from initial analysis until obsolescence • Formal process for software development • Describes phases of the development process • Gives guidelines for how to carry out the phases • Development process • • • Analysis Design Implementation Testing Deployment Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Analysis • Decide what the project is suppose to do • Do not think

Analysis • Decide what the project is suppose to do • Do not think about how the program will accomplish tasks • Output: requirements document • Describes what program will do once completed • User manual: tells how user will operate program • Performance criteria Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Design • Plan how to implement the system • Discover structures that underlie problem

Design • Plan how to implement the system • Discover structures that underlie problem to be solved • Decide what classes and methods you need • Output: • Description of classes and methods • Diagrams showing the relationships among the classes Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Implementation • Write and compile the code • Code implements classes and methods discovered

Implementation • Write and compile the code • Code implements classes and methods discovered in the design phase • Output: completed program Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Testing • Run tests to verify the program works correctly • Output: a report

Testing • Run tests to verify the program works correctly • Output: a report of the tests and their results Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Deployment • Users install program • Users use program for its intended purpose Big

Deployment • Users install program • Users use program for its intended purpose Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

The Waterfall Model • Sequential process of analysis, design, implementation, testing, and deployment •

The Waterfall Model • Sequential process of analysis, design, implementation, testing, and deployment • When rigidly applied, waterfall model did not work Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

The Spiral Model • Breaks development process down into multiple phases • Early phases

The Spiral Model • Breaks development process down into multiple phases • Early phases focus on the construction of prototypes • Lessons learned from development of one prototype can be applied to the next iteration • Problem: can lead to many iterations, and process can take too long to complete Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

The Spiral Model (cont. ) Big Java by Cay Horstmann Copyright © 2008 by

The Spiral Model (cont. ) Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Activity Levels in the Rational Unified Process • Development process methodology by the inventors

Activity Levels in the Rational Unified Process • Development process methodology by the inventors of UML Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Extreme Programming • Strives for simplicity • Removes formal structure • Focuses on best

Extreme Programming • Strives for simplicity • Removes formal structure • Focuses on best practices • • • Realistic planning Small releases Metaphor Simplicity Testing Refactoring Pair programming Collective ownership Continuous integration 40 -hour week On-site customer Coding standards Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Extreme Programming Realistic planning • Customers make business decisions • Programmers make technical decisions

Extreme Programming Realistic planning • Customers make business decisions • Programmers make technical decisions • Update plan when it conflicts with reality • Small releases • Release a useful system quickly • Release updates on a very short cycle • Metaphor • Programmers have a simple shared story that explains the system Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Extreme Programming • Simplicity • Design as simply as possible instead of preparing for

Extreme Programming • Simplicity • Design as simply as possible instead of preparing for future complexities • Testing • Programmers and customers write test cases • Test continuously • Refactoring • Restructure the system continuously to improve code and eliminate duplication Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Extreme Programming • Pair programming • Two programmers write code on the same computer

Extreme Programming • Pair programming • Two programmers write code on the same computer • Collective ownership • All programmers can change all code as needed • Continuous integration • Build the entire system and test it whenever a task is complete Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Extreme Programming • 40 -hour week • Don't cover up unrealistic schedules with heroic

Extreme Programming • 40 -hour week • Don't cover up unrealistic schedules with heroic effort • On-site customer • A customer is accessible to the programming team at all times • Coding standards • Follow standards that emphasize self-documenting code Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 1 Suppose you sign a contract, promising that you will, for

Self Check 12. 1 Suppose you sign a contract, promising that you will, for an agreed-upon price, design, implement, and test a software package exactly as it has been specified in a requirements document. What is the primary risk you and your customer are facing with this business arrangement? Answer: It is unlikely that the customer did a perfect job with the requirements document. If you don't accommodate changes, your customer may not like the outcome. If you charge for the changes, your customer may not like the cost. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 2 Does Extreme Programming follow a waterfall or a spiral model?

Self Check 12. 2 Does Extreme Programming follow a waterfall or a spiral model? Answer: An "extreme" spiral model, with lots of iterations. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 3 What is the purpose of the "on-site customer" in Extreme

Self Check 12. 3 What is the purpose of the "on-site customer" in Extreme Programming? Answer: To give frequent feedback as to whether the current iteration of the product fits customer needs. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Object-Oriented Design • Discover classes • Determine responsibilities of each class • Describe relationships

Object-Oriented Design • Discover classes • Determine responsibilities of each class • Describe relationships between the classes Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Discovering Classes • A class represents some useful concept • Concrete entities: bank accounts,

Discovering Classes • A class represents some useful concept • Concrete entities: bank accounts, ellipses, and products • Abstract concepts: streams and windows • Find classes by looking for nouns in the task description • Define the behavior for each class • Find methods by looking for verbs in the task description Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Example: Invoice Big Java by Cay Horstmann Copyright © 2008 by John Wiley &

Example: Invoice Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Example: Invoice • Classes that come to mind: Invoice, Line. Item, and Customer •

Example: Invoice • Classes that come to mind: Invoice, Line. Item, and Customer • Good idea to keep a list of candidate classes • Brainstorm, simply put all ideas for classes onto the list • You can cross not useful ones later Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Finding Classes • Keep the following points in mind: • Class represents set of

Finding Classes • Keep the following points in mind: • Class represents set of objects with the same behavior o Entities with multiple occurrences in problem description are good candidates for objects o Find out what they have in common o Design classes to capture commonalities • Represent some entities as objects, others as primitive types o Should we make a class Address or use a String? • Not all classes can be discovered in analysis phase • Some classes may already exist Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Card • Describes a class, its responsibilities, and its collaborators • Use an

CRC Card • Describes a class, its responsibilities, and its collaborators • Use an index card for each class • Pick the class that should be responsible for each method (verb) • Write the responsibility onto the class card • Indicate what other classes are needed to fulfill responsibility (collaborators) Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Card (cont. ) Big Java by Cay Horstmann Copyright © 2008 by John

CRC Card (cont. ) Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 4 Suppose the invoice is to be saved to a file.

Self Check 12. 4 Suppose the invoice is to be saved to a file. Name a likely collaborator. Answer: File. Writer Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 5 Looking at the invoice in Figure 4, what is a

Self Check 12. 5 Looking at the invoice in Figure 4, what is a likely responsibility of the Customer class? Answer: To produce the shipping address of the customer. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 6 What do you do if a CRC card has ten

Self Check 12. 6 What do you do if a CRC card has ten responsibilities? Answer: Reword the responsibilities so that they are at a higher level, or come up with more classes to handle the responsibilities. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Relationships Between Classes • Inheritance • Aggregation • Dependency Big Java by Cay Horstmann

Relationships Between Classes • Inheritance • Aggregation • Dependency Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Inheritance • Is-a relationship • Relationship between a more general class (superclass) and a

Inheritance • Is-a relationship • Relationship between a more general class (superclass) and a more specialized class (subclass) • Every savings account is a bank account • Every circle is an ellipse (with equal width and height) • It is sometimes abused • Should the class Tire be a subclass of a class Circle? o The has-a relationship would be more appropriate Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Aggregation • Has-a relationship • Objects of one class contain references to objects of

Aggregation • Has-a relationship • Objects of one class contain references to objects of another class • Use an instance variable • A tire has a circle as its boundary: class Tire {. . . private String rating; private Circle boundary; } • Every car has a tire (in fact, it has four) Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Example class Car extends Vehicle {. . . private Tire[] tires; } Big Java

Example class Car extends Vehicle {. . . private Tire[] tires; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Dependency • Uses relationship • Example: many of our applications depend on the Scanner

Dependency • Uses relationship • Example: many of our applications depend on the Scanner class to read input • Aggregation is a stronger form of dependency • Use aggregation to remember another object between method calls Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

UML Relationship Symbols Relationship Symbol Line Style Arrow Tip Inheritance Solid Triangle Interface Implementation

UML Relationship Symbols Relationship Symbol Line Style Arrow Tip Inheritance Solid Triangle Interface Implementation Dotted Triangle Aggregation Solid Diamond Dependency Dotted Open Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 7 Consider the Bank and Bank. Account classes of Chapter 7.

Self Check 12. 7 Consider the Bank and Bank. Account classes of Chapter 7. How are they related? Answer: Through aggregation. The bank manages bank account objects. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 8 Consider the Bank. Account and Savings. Account objects of Chapter

Self Check 12. 8 Consider the Bank. Account and Savings. Account objects of Chapter 10. How are they related? Answer: Through inheritance. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 9 Consider the Bank. Account. Tester class of Chapter 3. Which

Self Check 12. 9 Consider the Bank. Account. Tester class of Chapter 3. Which classes does it depend on? Answer: The Bank. Account, System, and Print. Stream classes. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Advanced Topic: Attributes and Methods in UML Diagrams Big Java by Cay Horstmann Copyright

Advanced Topic: Attributes and Methods in UML Diagrams Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Advanced Topic: Multiplicities • • any number (zero or more): * one or more:

Advanced Topic: Multiplicities • • any number (zero or more): * one or more: 1. . * zero or one: 0. . 1 exactly one: 1 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Advanced Topic: Aggregation and Association • Association: more general relationship between classes • Use

Advanced Topic: Aggregation and Association • Association: more general relationship between classes • Use early in the design phase • A class is associated with another if you can navigate from objects of one class to objects of the other • Given a Bank object, you can navigate to Customer objects Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Five-Part Development Process 1. Gather requirements 2. Use CRC cards to find classes, responsibilities,

Five-Part Development Process 1. Gather requirements 2. Use CRC cards to find classes, responsibilities, and collaborators 3. Use UML diagrams to record class relationships 4. Use javadoc to document method behavior 5. Implement your program Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – Requirements • Task: print out an invoice • Invoice: describes

Printing an Invoice – Requirements • Task: print out an invoice • Invoice: describes the charges for a set of products in certain quantities • Omit complexities • Dates, taxes, and invoice and customer numbers • Print invoice • Billing address, all line items, amount due • Line item • Description, unit price, quantity ordered, total price • For simplicity, do not provide a user interface • Test program: adds line items to the invoice and then prints it Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Sample Invoice INVOICE Sam's Small Appliances 100 Main Street Anytown, CA 98765 Description Toaster

Sample Invoice INVOICE Sam's Small Appliances 100 Main Street Anytown, CA 98765 Description Toaster Hair dryer Car vacuum Price 29. 95 24. 95 19. 99 Qty 3 1 2 Total 89. 85 24. 95 39. 98 AMOUNT DUE: $154. 78 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – CRC Cards • Discover classes • Nouns are possible classes

Printing an Invoice – CRC Cards • Discover classes • Nouns are possible classes Invoice Address Line. Item Product Description Price Quantity Total Amount Due Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – CRC Cards • Analyze classes Invoice Address Line. Item //

Printing an Invoice – CRC Cards • Analyze classes Invoice Address Line. Item // Records the product and the quantity Product Description // Field of the Product class Price // Field of the Product class Quantity // Not an attribute of a Product Total // Computed – not stored anywhere Amount Due // Computed – not stored anywhere • Classes after a process of elimination Invoice Address Line. Item Product Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Printing Invoice and Address must be able to format themselves: Big

CRC Cards for Printing Invoice and Address must be able to format themselves: Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Printing Invoice Add collaborators to invoice card: Big Java by Cay

CRC Cards for Printing Invoice Add collaborators to invoice card: Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Printing Invoice Product and Line. Item CRC cards: Big Java by

CRC Cards for Printing Invoice Product and Line. Item CRC cards: Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Printing Invoice must be populated with products and quantities: Big Java

CRC Cards for Printing Invoice must be populated with products and quantities: Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – UML Diagrams Big Java by Cay Horstmann Copyright © 2008

Printing an Invoice – UML Diagrams Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – Method Documentation • Use javadoc documentation to record the behavior

Printing an Invoice – Method Documentation • Use javadoc documentation to record the behavior of the classes • Leave the body of the methods blank • Run javadoc to obtain formatted version of documentation in HTML format • Advantages: • Share HTML documentation with other team members • Format is immediately useful: Java source files • Supply the comments of the key methods Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Invoice class /** Describes an invoice for a set of purchased

Method Documentation – Invoice class /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Adds a charge for a product to this invoice. @param a. Product the product that the customer ordered @param quantity the quantity of the product */ public void add(Product a. Product, int quantity) { } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Invoice class (cont. ) /** Formats the invoice. @return the formatted

Method Documentation – Invoice class (cont. ) /** Formats the invoice. @return the formatted invoice */ public String format() { } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Line. Item class /** Describes a quantity of an article to

Method Documentation – Line. Item class /** Describes a quantity of an article to purchase and its price. */ public class Line. Item { /** Computes the total cost of this line item. @return the total price */ public double get. Total. Price() { } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Line. Item class (cont. ) /** Formats this item. @return a

Method Documentation – Line. Item class (cont. ) /** Formats this item. @return a formatted string of this line item */ public String format() { } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Product class /** Describes a product with a description and a

Method Documentation – Product class /** Describes a product with a description and a price. */ public class Product { /** Gets the product description. @return the description */ public String get. Description() { } /** Gets the product price. @return the unit price Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Product class (cont. ) */ public double get. Price() { }

Method Documentation – Product class (cont. ) */ public double get. Price() { } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation – Address class /** Describes a mailing address. */ public class Address

Method Documentation – Address class /** Describes a mailing address. */ public class Address { /** Formats the address. @return the address as a string with three lines */ public String format() { } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

The Class Documentation in the HTML Format Big Java by Cay Horstmann Copyright ©

The Class Documentation in the HTML Format Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Printing an Invoice – Implementation • The UML diagram will give instance variables •

Printing an Invoice – Implementation • The UML diagram will give instance variables • Look for associated classes • They yield instance variables Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Implementation • Invoice aggregates Address and Line. Item • Every invoice has one billing

Implementation • Invoice aggregates Address and Line. Item • Every invoice has one billing address • An invoice can have many line items: public class Invoice {. . . private Address billing. Address; private Array. List<Line. Item> items; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Implementation A line item needs to store a Product object and quantity: public class

Implementation A line item needs to store a Product object and quantity: public class Line. Item {. . . private int quantity; private Product the. Product; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Implementation • The methods themselves are now very easy • Example: • get. Total.

Implementation • The methods themselves are now very easy • Example: • get. Total. Price of Line. Item gets the unit price of the product and multiplies it with the quantity /** Computes the total cost of this line item. @return the total price */ public double get. Total. Price() { return the. Product. get. Price() * quantity; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Invoice. Printer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

ch 12/invoice/Invoice. Printer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: /** This program demonstrates the invoice classes by printing a sample invoice. */ public class Invoice. Printer { public static void main(String[] args) { Address sams. Address = new Address("Sam's Small Appliances", "100 Main Street", "Anytown", "CA", "98765"); Invoice sams. Invoice. add(new = new Invoice(sams. Address); Product("Toaster", 29. 95), 3); Product("Hair dryer", 24. 95), 1); Product("Car vacuum", 19. 99), 2); System. out. println(sams. Invoice. format()); } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Invoice. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/invoice/Invoice. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: import java. util. Array. List; /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Constructs an invoice. @param an. Address the billing address */ public Invoice(Address an. Address) { items = new Array. List<Line. Item>(); billing. Address = an. Address; } /** Adds a charge for a product to this invoice. @param a. Product the product that the customer ordered @param quantity the quantity of the product Continued */ Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Invoice. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31:

ch 12/invoice/Invoice. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: public void add(Product a. Product, int quantity) { Line. Item an. Item = new Line. Item(a. Product, quantity); items. add(an. Item); } /** Formats the invoice. @return the formatted invoice */ public String format() { String r = " I N V O I C Enn" + billing. Address. format() + String. format("nn%-30 s%8 s%5 s%8 sn", "Description", "Price", "Qty", "Total"); for (Line. Item i : items) { r = r + i. format() + "n"; } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Invoice. java (cont. ) 45: 46: 47: 48: 49: 50: 51: 52: 53:

ch 12/invoice/Invoice. java (cont. ) 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: } r = r + String. format("n. AMOUNT DUE: $%8. 2 f", get. Amount. Due()); return r; } /** Computes the total amount due. @return the amount due */ public double get. Amount. Due() { double amount. Due = 0; for (Line. Item i : items) { amount. Due = amount. Due + i. get. Total. Price(); } return amount. Due; } private Address billing. Address; private Array. List<Line. Item> items; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Line. Item. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

ch 12/invoice/Line. Item. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: /** Describes a quantity of an article to purchase. */ public class Line. Item { /** Constructs an item from the product and quantity. @param a. Product the product @param a. Quantity the item quantity */ public Line. Item(Product a. Product, int a. Quantity) { the. Product = a. Product; quantity = a. Quantity; } /** Computes the total cost of this line item. @return the total price */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Line. Item. java (cont. ) 21: 22: 23: 24: 25: 26: 27: 28:

ch 12/invoice/Line. Item. java (cont. ) 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: } public double get. Total. Price() { return the. Product. get. Price() * quantity; } /** Formats this item. @return a formatted string of this item */ public String format() { return String. format("%-30 s%8. 2 f%5 d%8. 2 f", the. Product. get. Description(), the. Product. get. Price(), quantity, get. Total. Price()); } private int quantity; private Product the. Product; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Product. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/invoice/Product. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: /** Describes a product with a description and a price. */ public class Product { /** Constructs a product from a description and a price. @param a. Description the product description @param a. Price the product price */ public Product(String a. Description, double a. Price) { description = a. Description; price = a. Price; } /** Gets the product description. @return the description */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Product. java (cont. ) 21: 22: 23: 24: 25: 26: 27: 28: 29:

ch 12/invoice/Product. java (cont. ) 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: } 38: public String get. Description() { return description; } /** Gets the product price. @return the unit price */ public double get. Price() { return price; } private String description; private double price; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Address. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/invoice/Address. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: /** Describes a mailing address. */ public class Address { /** Constructs a mailing address. @param a. Name the recipient name @param a. Street the street @param a. City the city @param a. State the two-letter state code @param a. Zip the ZIP postal code */ public Address(String a. Name, String a. Street, String a. City, String a. State, String a. Zip) { name = a. Name; street = a. Street; city = a. City; state = a. State; zip = a. Zip; } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/invoice/Address. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31:

ch 12/invoice/Address. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: } 40: /** Formats the address. @return the address as a string with three lines */ public String format() { return name + "n" + street + "n" + city + ", " + state + " " + zip; } private private String String name; street; city; state; zip; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 10 Which class is responsible for computing the amount due? What

Self Check 12. 10 Which class is responsible for computing the amount due? What are its collaborators for this task? Answer: The Invoice class is responsible for computing the amount due. It collaborates with the Line. Item class. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 11 Why do the format methods return String objects instead of

Self Check 12. 11 Why do the format methods return String objects instead of directly printing to System. out? Answer: This design decision reduces coupling. It enables us to reuse the classes when we want to show the invoice in a dialog box or on a web page. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • ATM is used by bank customers. A

An Automatic Teller Machine – Requirements • ATM is used by bank customers. A customer has a • • Checking account Savings account Customer number PIN Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • Customers can select an account • The

An Automatic Teller Machine – Requirements • Customers can select an account • The balance of the selected account is displayed • Then, customer can deposit and withdraw money • Process is repeated until the customer chooses to exit Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • GUI Interface • • Keypad Display Buttons

An Automatic Teller Machine – Requirements • GUI Interface • • Keypad Display Buttons A, B, C Buttons function depend on the state of the machine Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • At start up the customer is expected

An Automatic Teller Machine – Requirements • At start up the customer is expected to • Enter customer number • Press the A button • The display shows: Enter Customer Number A = OK Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • The customer is expected to • Enter

An Automatic Teller Machine – Requirements • The customer is expected to • Enter a PIN • Press A button • The display shows: Enter PIN A = OK Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • Search for the customer number and PIN

An Automatic Teller Machine – Requirements • Search for the customer number and PIN • If it matches a bank customer, proceed • Else return to start up screen Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • If the customer is authorized • The

An Automatic Teller Machine – Requirements • If the customer is authorized • The display shows: Select Account A = Checking B = Savings C = Exit Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • If the user presses C • The

An Automatic Teller Machine – Requirements • If the user presses C • The ATM reverts to its original state • ATM asks next user to enter a customer number • If the user presses A or B • The ATM remembers selected account • The display shows: Balance = balance of selected account Enter amount and select transaction A = Withdraw B = Deposit C = Cancel Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • If the user presses A or B

An Automatic Teller Machine – Requirements • If the user presses A or B • The value entered is withdrawn or deposited • Simulation: no money is dispensed and no deposit is accepted • The ATM reverts to previous state • If the user presses C • The ATM reverts to previous state Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Requirements • Text-based interaction • Read input from System.

An Automatic Teller Machine – Requirements • Text-based interaction • Read input from System. in instead of the buttons • Here is a typical dialog: Enter account number: 1 Enter PIN: 1234 A=Checking, B=Savings, C=Quit: A Balance=0. 0 A=Deposit, B=Withdrawal, C=Cancel: A Amount: 1000 A=Checking, B=Savings, C=Quit: C Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – CRC Nouns are possible classes ATM User Keypad Display

An Automatic Teller Machine – CRC Nouns are possible classes ATM User Keypad Display message Button State Bank account Checking account Savings account Customer number PIN Bank Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Automatic Teller Machine Big Java by Cay Horstmann Copyright © 2008

CRC Cards for Automatic Teller Machine Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

CRC Cards for Automatic Teller Machine (cont. ) Big Java by Cay Horstmann Copyright

CRC Cards for Automatic Teller Machine (cont. ) Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ATM States 1. 2. 3. 4. START: Enter customer ID PIN: Enter PIN ACCOUNT:

ATM States 1. 2. 3. 4. START: Enter customer ID PIN: Enter PIN ACCOUNT: Select account TRANSACT: Select transaction Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

State Diagram for ATM Class Big Java by Cay Horstmann Copyright © 2008 by

State Diagram for ATM Class Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – UML Diagrams Big Java by Cay Horstmann Copyright ©

An Automatic Teller Machine – UML Diagrams Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation ATM Class /** An ATM that accesses a bank. */ public class

Method Documentation ATM Class /** An ATM that accesses a bank. */ public class ATM { /** Constructs an ATM for a given bank. @param a. Bank the bank to which this ATM connects */ public ATM(Bank a. Bank) { } /** Sets the current customer number and sets state to PIN. (Precondition: state is START) @param number the customer number */ public void set. Customer. Number(int number) { } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation ATM Class (Continued) /** Finds customer in bank. If found sets state

Method Documentation ATM Class (Continued) /** Finds customer in bank. If found sets state to ACCOUNT, else to START. (Precondition: state is PIN) @param pin the PIN of the current customer */ public void select. Customer(int pin) { } /** Sets current account to checking or savings. Sets state to TRANSACT. (Precondition: state is ACCOUNT or TRANSACT) @param account one of CHECKING or SAVINGS */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Method Documentation ATM Class (Continued) public void select. Account(int account) { } /** Withdraws

Method Documentation ATM Class (Continued) public void select. Account(int account) { } /** Withdraws amount from current account. (Precondition: state is TRANSACT) @param value the amount to withdraw */ public void withdraw(double value) { }. . . } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Implementation • Start implementation with classes that don't depend

An Automatic Teller Machine – Implementation • Start implementation with classes that don't depend on others • Keypad • Bank. Account • Then implement Customer which depends only on Bank. Account • This bottom-up approach allows you to test your classes individually Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Implementation • Aggregated classes in UML diagram give instance

An Automatic Teller Machine – Implementation • Aggregated classes in UML diagram give instance variables public class ATM {. . . private Bank the. Bank; } • From description of ATM states, it is clear that we require additional instance variables: public class ATM {. . . private int state; private Customer current. Customer; private Bank. Account current. Account; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Implementation • Most methods are very straightforward to implement

An Automatic Teller Machine – Implementation • Most methods are very straightforward to implement • Consider select. Customer: /** Finds customer in bank. If found sets state to ACCOUNT, else to START. (Precondition: state is PIN) @param pin the PIN of the current customer */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

An Automatic Teller Machine – Implementation • Description can be almost literally translated to

An Automatic Teller Machine – Implementation • Description can be almost literally translated to Java instructions: public void select. Customer(int pin) { assert state == PIN; current. Customer = the. Bank. find. Customer(customer. Number, pin); if (current. Customer == null) state = START; else state = ACCOUNT; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011:

ch 12/atm/ATM. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: /** An ATM that accesses a bank. */ public class ATM { /** Constructs an ATM for a given bank. @param a. Bank the bank to which this ATM connects */ public ATM(Bank a. Bank) { the. Bank = a. Bank; reset(); } /** Resets the ATM to the initial state. */ public void reset() { Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 021: 022: 023: 024: 025: 026: 027: 028: 029:

ch 12/atm/ATM. java (cont. ) 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: 041: customer. Number = -1; current. Account = null; state = START; } /** Sets the current customer number and sets state to PIN. (Precondition: state is START) @param number the customer number. */ public void set. Customer. Number(int number) { assert state == START; customer. Number = number; state = PIN; } /** Finds customer in bank. If found sets state to ACCOUNT, else to START. Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 042: 043: 044: 045: 046: 047: 048: 049: 050:

ch 12/atm/ATM. java (cont. ) 042: 043: 044: 045: 046: 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: (Precondition: state is PIN) @param pin the PIN of the current customer */ public void select. Customer(int pin) { assert state == PIN; current. Customer = the. Bank. find. Customer(customer. Number, pin); if (current. Customer == null) state = START; else state = ACCOUNT; } /** Sets current account to checking or savings. Sets state to TRANSACT. (Precondition: state is ACCOUNT or TRANSACT) @param account one of CHECKING or SAVINGS */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 062: 063: 064: 065: 066: 067: 068: 069: 070:

ch 12/atm/ATM. java (cont. ) 062: 063: 064: 065: 066: 067: 068: 069: 070: 071: 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: public void select. Account(int account) { assert state == ACCOUNT || state == TRANSACT; if (account == CHECKING) current. Account = current. Customer. get. Checking. Account(); else current. Account = current. Customer. get. Savings. Account(); state = TRANSACT; } /** Withdraws amount from current account. (Precondition: state is TRANSACT) @param value the amount to withdraw */ public void withdraw(double value) { assert state == TRANSACT; current. Account. withdraw(value); } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 083: 084: 085: 086: 087: 088: 089: 090: 091:

ch 12/atm/ATM. java (cont. ) 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: /** Deposits amount to current account. (Precondition: state is TRANSACT) @param value the amount to deposit */ public void deposit(double value) { assert state == TRANSACT; current. Account. deposit(value); } /** Gets the balance of the current account. (Precondition: state is TRANSACT) @return the balance */ public double get. Balance() { assert state == TRANSACT; return current. Account. get. Balance(); } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 104: 105: 106: 107: 108: 109: 110: 111: 112:

ch 12/atm/ATM. java (cont. ) 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: /** Moves back to the previous state. */ public void back() { if (state == TRANSACT) state = ACCOUNT; else if (state == ACCOUNT) state = PIN; else if (state == PIN) state = START; } /** Gets the current state of this ATM. @return the current state */ public int get. State() { return state; } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATM. java (cont. ) 126: 127: 128: 129: 130: 131: 132: 133: 134:

ch 12/atm/ATM. java (cont. ) 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: } private private public int state; int customer. Number; Customer current. Customer; Bank. Account current. Account; Bank the. Bank; static final int int START = 1; PIN = 2; ACCOUNT = 3; TRANSACT = 4; public static final int CHECKING = 1; public static final int SAVINGS = 2; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Bank. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/atm/Bank. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: import java. io. File. Reader; java. io. IOException; java. util. Array. List; java. util. Scanner; /** A bank contains customers with bank accounts. */ public class Bank { /** Constructs a bank with no customers. */ public Bank() { customers = new Array. List<Customer>(); } /** Reads the customer numbers and pins and initializes the bank accounts. @param filename the name of the customer file */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Bank. java (cont. ) 24: 25: 26: 27: 28: 29: 30: 31: 32:

ch 12/atm/Bank. java (cont. ) 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: public void read. Customers(String filename) throws IOException { Scanner in = new Scanner(new File. Reader(filename)); while (in. has. Next()) { int number = in. next. Int(); int pin = in. next. Int(); Customer c = new Customer(number, pin); add. Customer(c); } in. close(); } /** Adds a customer to the bank. @param c the customer to add */ public void add. Customer(Customer c) { customers. add(c); } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Bank. java (cont. ) 46: 47: 48: 49: 50: 51: 52: 53: 54:

ch 12/atm/Bank. java (cont. ) 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: } 66: 67: /** Finds a customer in the bank. @param a. Number a customer number @param a. Pin a personal identification number @return the matching customer, or null if no customer matches */ public Customer find. Customer(int a. Number, int a. Pin) { for (Customer c : customers) { if (c. match(a. Number, a. Pin)) return c; } return null; } private Array. List<Customer> customers; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Customer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/atm/Customer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: /** A bank customer with a checking and a savings account. */ public class Customer { /** Constructs a customer with a given number and PIN. @param a. Number the customer number @param a. Pin the personal identification number */ public Customer(int a. Number, int a. Pin) { customer. Number = a. Number; pin = a. Pin; checking. Account = new Bank. Account(); savings. Account = new Bank. Account(); } /** Tests if this customer matches a customer number Continued and PIN. @param a. Number a customer number Big Java by Cay Horstmann @param a. Pin a personal identification number Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Customer. java (cont. ) 24: 25: 26: 27: 28: 29: 30: 31: 32:

ch 12/atm/Customer. java (cont. ) 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: @return true if the customer number and PIN match */ public boolean match(int a. Number, int a. Pin) { return customer. Number == a. Number && pin == a. Pin; } /** Gets the checking account of this customer. @return the checking account */ public Bank. Account get. Checking. Account() { return checking. Account; } /** Gets the savings account of this customer. @return the checking account */ public Bank. Account get. Savings. Account() { Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/Customer. java (cont. ) 46: 47: 48: 49: 50: 51: 52: 53: }

ch 12/atm/Customer. java (cont. ) 46: 47: 48: 49: 50: 51: 52: 53: } return savings. Account; } private int customer. Number; int pin; Bank. Account checking. Account; Bank. Account savings. Account; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMSimulator. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/atm/ATMSimulator. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: import java. io. IOException; import java. util. Scanner; /** A text-based simulation of an automatic teller machine. */ public class ATMSimulator { public static void main(String[] args) { ATM the. ATM; try { Bank the. Bank = new Bank(); the. Bank. read. Customers("customers. txt"); the. ATM = new ATM(the. Bank); } catch(IOException e) { System. out. println("Error opening accounts file. "); return; } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMSimulator. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31:

ch 12/atm/ATMSimulator. java (cont. ) 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: Scanner in = new Scanner(System. in); while (true) { int state = the. ATM. get. State(); if (state == ATM. START) { System. out. print("Enter customer number: "); int number = in. next. Int(); the. ATM. set. Customer. Number(number); } else if (state == ATM. PIN) { System. out. print("Enter PIN: "); int pin = in. next. Int(); the. ATM. select. Customer(pin); } else if (state == ATM. ACCOUNT) { System. out. print("A=Checking, B=Savings, C=Quit: "); String command = in. next(); Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMSimulator. java (cont. ) 45: 46: 47: 48: 49: 50: 51: 52: 53:

ch 12/atm/ATMSimulator. java (cont. ) 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: if (command. equals. Ignore. Case("A")) the. ATM. select. Account(ATM. CHECKING); else if (command. equals. Ignore. Case("B")) the. ATM. select. Account(ATM. SAVINGS); else if (command. equals. Ignore. Case("C")) the. ATM. reset(); else System. out. println("Illegal input!"); } else if (state == ATM. TRANSACT) { System. out. println("Balance=" + the. ATM. get. Balance()); System. out. print("A=Deposit, B=Withdrawal, C=Cancel: "); String command = in. next(); if (command. equals. Ignore. Case("A")) { System. out. print("Amount: "); double amount = in. next. Double(); the. ATM. deposit(amount); the. ATM. back(); } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMSimulator. java (cont. ) 66: 67: 68: 69: 70: 71: 72: 73: 74:

ch 12/atm/ATMSimulator. java (cont. ) 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: } 81: else if (command. equals. Ignore. Case("B")) { System. out. print("Amount: "); double amount = in. next. Double(); the. ATM. withdraw(amount); the. ATM. back(); } else if (command. equals. Ignore. Case("C")) the. ATM. back(); else System. out. println("Illegal input!"); } } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMSimulator. java (cont. ) Enter account number: 1 Enter PIN: 1234 A=Checking, B=Savings,

ch 12/atm/ATMSimulator. java (cont. ) Enter account number: 1 Enter PIN: 1234 A=Checking, B=Savings, C=Quit: A Balance=0. 0 A=Deposit, B=Withdrawal, C=Cancel: A Amount: 1000 A=Checking, B=Savings, C=Quit: C. . . Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMViewer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

ch 12/atm/ATMViewer. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: import java. io. IOException; import javax. swing. JFrame; import javax. swing. JOption. Pane; /** A graphical simulation of an automatic teller machine. */ public class ATMViewer { public static void main(String[] args) { ATM the. ATM; try { Bank the. Bank = new Bank(); the. Bank. read. Customers("customers. txt"); the. ATM = new ATM(the. Bank); } catch(IOException e) { Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMViewer. java (cont. ) 22: 23: 24: 25: 26: 27: 28: 29: 30:

ch 12/atm/ATMViewer. java (cont. ) 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: } 33: JOption. Pane. show. Message. Dialog(null, "Error opening accounts file. "); return; } JFrame frame = new ATMFrame(the. ATM); frame. set. Title("First National Bank of Java"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Visible(true); } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMFrame. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011:

ch 12/atm/ATMFrame. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: 021: 022: import import java. awt. Flow. Layout; java. awt. Grid. Layout; java. awt. event. Action. Event; java. awt. event. Action. Listener; javax. swing. JButton; javax. swing. JFrame; javax. swing. JPanel; javax. swing. JText. Area; /** A frame displaying the components of an ATM. */ public class ATMFrame extends JFrame { /** Constructs the user interface of the ATM frame. */ public ATMFrame(ATM an. ATM) { the. ATM = an. ATM; // Construct components Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMFrame. java (cont. ) 023: 024: 025: 026: 027: 028: 029: 030: 031:

ch 12/atm/ATMFrame. java (cont. ) 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: 041: 042: 043: 044: 045: 046: pad = new Key. Pad(); display = new JText. Area(4, 20); a. Button = new JButton(" A "); a. Button. add. Action. Listener(new AButton. Listener()); b. Button = new JButton(" B "); b. Button. add. Action. Listener(new BButton. Listener()); c. Button = new JButton(" C "); c. Button. add. Action. Listener(new CButton. Listener()); // Add components JPanel button. Panel = new JPanel(); //button. Panel. set. Layout(new Grid. Layout(3, 1)); button. Panel. add(a. Button); button. Panel. add(b. Button); button. Panel. add(c. Button); set. Layout(new Flow. Layout()); add(pad); add(display); Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMFrame. java (cont. ) 047: 048: 049: 050: 051: 052: 053: 054: 055:

ch 12/atm/ATMFrame. java (cont. ) 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: 062: 063: 064: 065: 066: 067: 068: 069: add(button. Panel); show. State(); set. Size(FRAME_WIDTH, FRAME_HEIGHT); } /** Updates display message. */ public void show. State() { int state = the. ATM. get. State(); pad. clear(); if (state == ATM. START) display. set. Text("Enter customer numbern. A = OK"); else if (state == ATM. PIN) display. set. Text("Enter PINn. A = OK"); else if (state == ATM. ACCOUNT) display. set. Text("Select Accountn" + "A = Checkingn. B = Savingsn. C = Exit"); else if (state == ATM. TRANSACT) Continued display. set. Text("Balance = " + the. ATM. get. Balance() Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMFrame. java (cont. ) 070: 071: 072: 073: 074: 075: 076: 077: 078:

ch 12/atm/ATMFrame. java (cont. ) 070: 071: 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: + "n. Enter amount and select transactionn" + "A = Withdrawn. B = Depositn. C = Cancel"); } private class AButton. Listener implements Action. Listener { public void action. Performed(Action. Event event) { int state = the. ATM. get. State(); if (state == ATM. START) the. ATM. set. Customer. Number((int) pad. get. Value()); else if (state == ATM. PIN) the. ATM. select. Customer((int) pad. get. Value()); else if (state == ATM. ACCOUNT) the. ATM. select. Account(ATM. CHECKING); else if (state == ATM. TRANSACT) { the. ATM. withdraw(pad. get. Value()); the. ATM. back(); } show. State(); Continued } } Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

ch 12/atm/ATMFrame. java (cont. ) 093: 094: 095: 096: 097: 098: 099: 100: 101:

ch 12/atm/ATMFrame. java (cont. ) 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: private class BButton. Listener implements Action. Listener { public void action. Performed(Action. Event event) { int state = the. ATM. get. State(); if (state == ATM. ACCOUNT) the. ATM. select. Account(ATM. SAVINGS); else if (state == ATM. TRANSACT) { the. ATM. deposit(pad. get. Value()); the. ATM. back(); } show. State(); } } private class CButton. Listener implements Action. Listener { public void action. Performed(Action. Event event) Continued { int state = the. ATM. get. State(); if (state == ATM. ACCOUNT) Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. the. ATM. reset();

ch 12/atm/ATMFrame. java (cont. ) 117: 118: 119: 120: 121: 122: 123: 124: 125:

ch 12/atm/ATMFrame. java (cont. ) 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: } else if (state == ATM. TRANSACT) the. ATM. back(); show. State(); } } private JButton a. Button; private JButton b. Button; private JButton c. Button; private Key. Pad pad; private JText. Area display; private ATM the. ATM; private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 400; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

File Key. Pad. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010:

File Key. Pad. java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: 021: 022: 023: import import java. awt. Border. Layout; java. awt. Grid. Layout; java. awt. event. Action. Event; java. awt. event. Action. Listener; javax. swing. JButton; javax. swing. JPanel; javax. swing. JText. Field; /** A component that lets the user enter a number, using a button pad labeled with digits. */ public class Key. Pad extends JPanel { /** Constructs the keypad panel. */ public Key. Pad() { set. Layout(new Border. Layout()); Continued // Add display field Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

File Key. Pad. java (cont. ) 024: 025: 026: 027: 028: 029: 030: 031:

File Key. Pad. java (cont. ) 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: 041: 042: 043: 044: 045: 046: display = new JText. Field(); add(display, "North"); // Make button panel button. Panel = new JPanel(); button. Panel. set. Layout(new Grid. Layout(4, 3)); // Add digit buttons add. Button("7"); add. Button("8"); add. Button("9"); add. Button("4"); add. Button("5"); add. Button("6"); add. Button("1"); add. Button("2"); add. Button("3"); add. Button("0"); add. Button(". "); // Add clear entry button Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

File Key. Pad. java (cont. ) 047: 048: 049: 050: 051: 052: 053: 054:

File Key. Pad. java (cont. ) 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: 062: 063: 064: 065: 066: 067: 068: 069: clear. Button = new JButton("CE"); button. Panel. add(clear. Button); class Clear. Button. Listener implements Action. Listener { public void action. Performed(Action. Event event) { display. set. Text(""); } } Action. Listener listener = new Clear. Button. Listener(); clear. Button. add. Action. Listener(new Clear. Button. Listener()); add(button. Panel, "Center"); } /** Adds a button to the button panel @param label the button label */ Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

File Key. Pad. java (cont. ) 070: 071: 072: 073: 074: 075: 076: 077:

File Key. Pad. java (cont. ) 070: 071: 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: private void add. Button(final String label) { class Digit. Button. Listener implements Action. Listener { public void action. Performed(Action. Event event) { // Don't add two decimal points if (label. equals(". ") && display. get. Text(). index. Of(". ") != -1) return; // Append label text to button display. set. Text(display. get. Text() + label); } } JButton button = new JButton(label); button. Panel. add(button); Action. Listener listener = new Digit. Button. Listener(); button. add. Action. Listener(listener); } Continued Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

File Key. Pad. java (cont. ) 093: 094: 095: 096: 097: 098: 099: 100:

File Key. Pad. java (cont. ) 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: } 114: /** Gets the value that the user entered. @return the value in the text field of the keypad */ public double get. Value() { return Double. parse. Double(display. get. Text()); } /** Clears the display. */ public void clear() { display. set. Text(""); } private JPanel button. Panel; private JButton clear. Button; private JText. Field display; Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 12 Why does the Bank class in this example not store

Self Check 12. 12 Why does the Bank class in this example not store an array list of bank accounts? Answer: The bank needs to store the list of customers so that customers can log in. We need to locate all bank accounts of a customer, and we chose to simply store them in the customer class. In this program, there is no further need to access bank accounts. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.

Self Check 12. 13 Suppose the requirements change – you need to save the

Self Check 12. 13 Suppose the requirements change – you need to save the current account balances to a file after every transaction and reload them when the program starts. What is the impact of this change on the design? Answer: The Bank class needs to have an additional responsibility: to load and save the accounts. The bank can carry out this responsibility because it has access to the customer objects and, through them, to the bank accounts. Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved.