SlideShare ist ein Scribd-Unternehmen logo
1 von 137
Chapter 12 – Object-Oriented Design
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Analysis

• Decide what the project is supposed 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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Implementation
• Write and compile the code
• Code implements classes and methods discovered in the design
phase

• Program Run: Completed program

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Testing

• Run tests to verify the program works correctly
• Program Run: A report of the tests and their results

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Deployment
• Users install program

• Users use program for its intended purpose

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Spiral Model
• Problem: Can lead to many iterations, and process can take too
long to complete

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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Extreme Programming
• Strives for simplicity
• Removes formal structure
• Focuses on best practices

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Object-Oriented Design
1. Discover classes
2. Determine responsibilities of each class
3. Describe relationships between the classes

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Example: Invoice

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Example: Invoice
• Classes that come to mind: Invoice, LineItem, 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 © 2009 by John Wiley & Sons. All rights reserved.
Finding Classes

• Keep the following points in mind:
• Class represents set of objects with the same behavior
o
o
o

Entities with multiple occurrences in problem description are good
candidates for objects
Find out what they have in common
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 © 2009 by John Wiley & Sons. All rights reserved.
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

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
CRC Card
• Indicate what other classes are needed to fulfill responsibility
(collaborators)

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 12.4

Suppose the invoice is to be saved to a file. Name a likely
collaborator.
Answer: PrintStream

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Relationships Between Classes
• Inheritance
• Aggregation
• Dependency

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Example
class Car extends Vehicle
{
...
private Tire[] tires;
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Self Check 12.7
Consider the Bank and BankAccount classes of Chapter 7. How
are they related?
Answer: Through aggregation. The bank manages bank
account objects.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 12.8
Consider the BankAccount and SavingsAccount objects of
Chapter 10. How are they related?
Answer: Through inheritance.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 12.9
Consider the BankAccountTester class of Chapter 3. Which
classes does it depend on?
Answer: The BankAccount, System, and PrintStream
classes.

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

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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: Printing an Invoice — CRC Cards

• Discover classes
• Nouns are possible classes:
Invoice
Address
LineItem
Product
Description
Price
Quantity
Total
Amount Due

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Case Study: Printing an Invoice — CRC Cards
• Analyze classes:
Invoice
Address
LineItem
Product
Description
Price
Quantity
Total
Amount Due

// Records the product and the quantity
//
//
//
//
//

variable of the Product class
variable of the Product class
Not an attribute of a Product
Computed – not stored anywhere
Computed – not stored anywhere

• Classes after a process of elimination:
Invoice
Address
LineItem
Product
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
CRC Cards for Printing Invoice
Invoice and Address must be able to format themselves:

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

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

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

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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 aProduct the product that the customer
ordered
@param quantity the quantity of the product
*/
public void add(Product aProduct, int quantity)
{
}

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

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

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Method Documentation — LineItem Class (cont.)
/**
Formats this item.
@return a formatted string of this line item
*/
public String format()
{
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 getDescription()
{
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Method Documentation — Product Class (cont.)
/**
Gets the product price.
@return the unit price
*/
public double getPrice()
{
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
The Class Documentation in the HTML Format

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Implementation
• Invoice aggregates Address and LineItem
• Every invoice has one billing address
• An invoice can have many line items:
public class Invoice
{
...
private Address billingAddress;
private ArrayList<LineItem> items;
}

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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Implementation
• The methods themselves are now very easy
• Example:
• getTotalPrice of LineItem 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 getTotalPrice()
{
return theProduct.getPrice() * quantity;
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/InvoicePrinter.java
1
2
3
4
5
6
7
8
9
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 InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress
= new Address("Sam&apos;s Small Appliances",
"100 Main Street", "Anytown", "CA", "98765");
Invoice samsInvoice
samsInvoice.add(new
samsInvoice.add(new
samsInvoice.add(new

= new Invoice(samsAddress);
Product("Toaster", 29.95), 3);
Product("Hair dryer", 24.95), 1);
Product("Car vacuum", 19.99), 2);

System.out.println(samsInvoice.format());

}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Invoice.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import java.util.ArrayList;
/**
Describes an invoice for a set of purchased products.
*/
public class Invoice
{
private Address billingAddress;
private ArrayList<LineItem> items;
/**
Constructs an invoice.
@param anAddress the billing address
*/
public Invoice(Address anAddress)
{
items = new ArrayList<LineItem>();
billingAddress = anAddress;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Invoice.java (cont.)
21
22
23
24
25
26
27
28
29
30
31

/**
Adds a charge for a product to this invoice.
@param aProduct the product that the customer ordered
@param quantity the quantity of the product
*/
public void add(Product aProduct, int quantity)
{
LineItem anItem = new LineItem(aProduct, quantity);
items.add(anItem);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Invoice.java (cont.)
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

/**
Formats the invoice.
@return the formatted invoice
*/
public String format()
{
String r = "
I N V O I C Enn"
+ billingAddress.format()
+ String.format("nn%-30s%8s%5s%8sn",
"Description", "Price", "Qty", "Total");
for (LineItem item : items)
{
r = r + item.format() + "n";
}
r = r + String.format("nAMOUNT DUE: $%8.2f", getAmountDue());

return r;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Invoice.java (cont.)
53
54
55
56
57
58
59
60
61
62
63
64
65
66

/**
Computes the total amount due.
@return the amount due
*/
public double getAmountDue()
{
double amountDue = 0;
for (LineItem item : items)
{
amountDue = amountDue + item.getTotalPrice();
}
return amountDue;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/LineItem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
Describes a quantity of an article to purchase.
*/
public class LineItem
{
private int quantity;
private Product theProduct;
/**
Constructs an item from the product and quantity.
@param aProduct the product
@param aQuantity the item quantity
*/
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/LineItem.java (cont.)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/**
Computes the total cost of this line item.
@return the total price
*/
public double getTotalPrice()
{
return theProduct.getPrice() * quantity;
}
/**
Formats this item.
@return a formatted string of this item
*/
public String format()
{
return String.format("%-30s%8.2f%5d%8.2f",
theProduct.getDescription(), theProduct.getPrice(),
quantity, getTotalPrice());
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Product.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
Describes a product with a description and a price.
*/
public class Product
{
private String description;
private double price;
/**
Constructs a product from a description and a price.
@param aDescription the product description
@param aPrice the product price
*/
public Product(String aDescription, double aPrice)
{
description = aDescription;
price = aPrice;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Product.java (cont.)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

/**
Gets the product description.
@return the description
*/
public String getDescription()
{
return description;
}

/**
Gets the product price.
@return the unit price
*/
public double getPrice()
{
return price;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Address.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
Describes a mailing address.
*/
public class Address
{
private String name;
private String street;
private String city;
private String state;
private String zip;
/**
Constructs a mailing address.
@param aName the recipient name
@param aStreet the street
@param aCity the city
@param aState the two-letter state code
@param aZip the ZIP postal code

*/

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/invoice/Address.java (cont.)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

public Address(String aName, String aStreet,
String aCity, String aState, String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
/**
Formats the address.
@return the address as a string with three lines
*/
public String format()
{
return name + "n" + street + "n"
+ city + ", " + state + " " + zip;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 LineItem class.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: An Automatic Teller Machine — Requirements
• Two separate interfaces:
• GUI that closely mimics an actual ATM
• Text-based interface

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Case Study: An Automatic Teller Machine — Requirements
• GUI Interface
• Keypad
• Display

• Buttons A, B, C
• Button functions depend on the state of the machine

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
An Automatic Teller Machine – CRC Cards
Nouns are possible classes:
ATM
User
Keypad
Display
Display message
Button
State
Bank account
Checking account
Savings account
Customer
Customer number
PIN
Bank
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
CRC Cards for Automatic Teller Machine

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

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

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

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

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

Continued

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Method Documentation ATM Class (cont.)
/**
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 selectCustomer(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 © 2009 by John Wiley & Sons. All rights reserved.
Method Documentation ATM Class (cont.)
public void selectAccount(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 © 2009 by John Wiley & Sons. All rights reserved.
An Automatic Teller Machine — Implementation
• Start implementation with classes that don’t depend on others
• Keypad
• BankAccount

• Then implement Customer which depends only on
BankAccount
• This bottom-up approach allows you to test your classes
individually

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
An Automatic Teller Machine — Implementation
• Aggregated classes in UML diagram give instance variables
public class ATM
{
private Bank theBank;
...
}

• From description of ATM states, it is clear that we require
additional instance variables:
public class ATM
{
private int state;
private Customer currentCustomer;
private BankAccount currentAccount;
...
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
An Automatic Teller Machine — Implementation
• Most methods are very straightforward to implement
• Consider selectCustomer:
/**
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 © 2009 by John Wiley & Sons. All rights reserved.
An Automatic Teller Machine — Implementation (cont.)
• Description can be almost literally translated to Java
instructions:
public void selectCustomer(int pin)
{
assert state == PIN;
currentCustomer = theBank.findCustomer(customerNumber,
pin);
if (currentCustomer == null)
state = START;
else
state = ACCOUNT;
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

/**
An ATM that accesses a bank.
*/
public class ATM
{
public static final int CHECKING = 1;
public static final int SAVINGS = 2;
private
private
private
private
private
public
public
public
public

int state;
int customerNumber;
Customer currentCustomer;
BankAccount currentAccount;
Bank theBank;
static
static
static
static

final
final
final
final

int
int
int
int

START = 1;
PIN = 2;
ACCOUNT = 3;
TRANSACT = 4;

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/**
Constructs an ATM for a given bank.
@param aBank the bank to which this ATM connects
*/
public ATM(Bank aBank)
{
theBank = aBank;
reset();
}
/**
Resets the ATM to the initial state.
*/
public void reset()
{
customerNumber = -1;
currentAccount = null;
state = START;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
40
41
42
43
44
45
46
47
48
49
50
51
52

/**
Sets the current customer number
and sets state to PIN.
(Precondition: state is START)
@param number the customer number.

*/
public void setCustomerNumber(int number)
{
assert state == START;
customerNumber = number;
state = PIN;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

/**
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 selectCustomer(int pin)
{
assert state == PIN;
currentCustomer = theBank.findCustomer(customerNumber, pin);
if (currentCustomer == null)
state = START;
else
state = ACCOUNT;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

/**
Sets current account to checking or savings. Sets
state to TRANSACT.
(Precondition: state is ACCOUNT or TRANSACT)
@param account one of CHECKING or SAVINGS

*/
public void selectAccount(int account)
{
assert state == ACCOUNT || state == TRANSACT;
if (account == CHECKING)
currentAccount = currentCustomer.getCheckingAccount();
else
currentAccount = currentCustomer.getSavingsAccount();
state = TRANSACT;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

/**
Withdraws amount from current account.
(Precondition: state is TRANSACT)
@param value the amount to withdraw
*/
public void withdraw(double value)
{
assert state == TRANSACT;
currentAccount.withdraw(value);
}
/**
Deposits amount to current account.
(Precondition: state is TRANSACT)
@param value the amount to deposit
*/
public void deposit(double value)
{
assert state == TRANSACT;
currentAccount.deposit(value);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

/**
Gets the balance of the current account.
(Precondition: state is TRANSACT)
@return the balance
*/
public double getBalance()
{
assert state == TRANSACT;
return currentAccount.getBalance();
}
/**
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;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATM.java (cont.)
131
132
133
134
135
136
137
138
139

/**
Gets the current state of this ATM.
@return the current state
*/
public int getState()
{
return state;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/Bank.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import
import
import
import

java.io.File;
java.io.IOException;
java.util.ArrayList;
java.util.Scanner;

/**
A bank contains customers with bank accounts.
*/
public class Bank
{
private ArrayList<Customer> customers;
/**
Constructs a bank with no customers.
*/
public Bank()
{
customers = new ArrayList<Customer>();
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/Bank.java (cont.)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/**
Reads the customer numbers and pins
and initializes the bank accounts.
@param filename the name of the customer file
*/
public void readCustomers(String filename)
throws IOException
{
Scanner in = new Scanner(new File(filename));
while (in.hasNext())
{
int number = in.nextInt();
int pin = in.nextInt();
Customer c = new Customer(number, pin);
addCustomer(c);
}
in.close();
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/Bank.java (cont.)
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/**

Adds a customer to the bank.
@param c the customer to add
*/
public void addCustomer(Customer c)
{
customers.add(c);
}
/**
Finds a customer in the bank.
@param aNumber a customer number
@param aPin a personal identification number
@return the matching customer, or null if no customer
matches
*/
public Customer findCustomer(int aNumber, int aPin)
{
for (Customer c : customers)
{
if (c.match(aNumber, aPin))
return c;
}
return null;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/Customer.java
1
2
3
4
5
6
7
8
9
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
{
private int customerNumber;
private int pin;
private BankAccount checkingAccount;
private BankAccount savingsAccount;
/**
Constructs a customer with a given number and PIN.
@param aNumber the customer number
@param aPin the personal identification number
*/
public Customer(int aNumber, int aPin)
{
customerNumber = aNumber;
pin = aPin;
checkingAccount = new BankAccount();
savingsAccount = new BankAccount();
}

Continued

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/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

/**
Tests if this customer matches a customer number
and PIN.
@param aNumber a customer number
@param aPin a personal identification number
@return true if the customer number and PIN match
*/
public boolean match(int aNumber, int aPin)
{
return customerNumber == aNumber && pin == aPin;
}
/**
Gets the checking account of this customer.
@return the checking account
*/
public BankAccount getCheckingAccount()
{
return checkingAccount;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/Customer.java (cont.)
45
46
47
48
49
50
51
52
53

/**
Gets the savings account of this customer.
@return the checking account
*/
public BankAccount getSavingsAccount()
{
return savingsAccount;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMSimulator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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 theATM;
try
{
Bank theBank = new Bank();
theBank.readCustomers("customers.txt");
theATM = new ATM(theBank);
}
catch(IOException e)
{
System.out.println("Error opening accounts file.");
return;
Continued
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMSimulator.java (cont.)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

Scanner in = new Scanner(System.in);
while (true)
{
int state = theATM.getState();
if (state == ATM.START)
{
System.out.print("Enter customer number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
}
else if (state == ATM.PIN)
{
System.out.print("Enter PIN: ");
int pin = in.nextInt();
theATM.selectCustomer(pin);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMSimulator.java (cont.)
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

else if (state == ATM.ACCOUNT)
{
System.out.print("A=Checking, B=Savings, C=Quit: ");
String command = in.next();
if (command.equalsIgnoreCase("A"))
theATM.selectAccount(ATM.CHECKING);
else if (command.equalsIgnoreCase("B"))
theATM.selectAccount(ATM.SAVINGS);
else if (command.equalsIgnoreCase("C"))
theATM.reset();
else
System.out.println("Illegal input!");
}
else if (state == ATM.TRANSACT)
{
System.out.println("Balance=" + theATM.getBalance());
System.out.print("A=Deposit, B=Withdrawal, C=Cancel: ");
String command = in.next();

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMSimulator.java (cont.)
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

if (command.equalsIgnoreCase("A"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.deposit(amount);
theATM.back();
}
else if (command.equalsIgnoreCase("B"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.withdraw(amount);
theATM.back();
}
else if (command.equalsIgnoreCase("C"))
theATM.back();
else
System.out.println("Illegal input!");

}
}
}
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMSimulator.java (cont.)
Program Run:
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 © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMViewer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
A graphical simulation of an automatic teller machine.
*/
public class ATMViewer
{
public static void main(String[] args)
{
ATM theATM;
try
{
Bank theBank = new Bank();
theBank.readCustomers("customers.txt");
theATM = new ATM(theBank);
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "Error opening accounts file.");
return;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMViewer.java (cont.)
26
27
28
29
30
31
32

JFrame frame = new ATMFrame(theATM);
frame.setTitle("First National Bank of Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import
import
import
import
import
import
import
import

java.awt.FlowLayout;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.JTextArea;

/**
A frame displaying the components of an ATM.
*/
public class ATMFrame extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 300;
private JButton aButton;
private JButton bButton;
private JButton cButton;
private KeyPad pad;
private JTextArea display;

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

private ATM theATM;
/**
Constructs the user interface of the ATM frame.

*/
public ATMFrame(ATM anATM)
{
theATM = anATM;
// Construct components
pad = new KeyPad();
display = new JTextArea(4, 20);
aButton = new JButton(" A ");
aButton.addActionListener(new AButtonListener());

bButton = new JButton(" B ");
bButton.addActionListener(new BButtonListener());

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

cButton = new JButton(" C ");
cButton.addActionListener(new CButtonListener());
// Add components

JPanel buttonPanel = new JPanel();
buttonPanel.add(aButton);
buttonPanel.add(bButton);
buttonPanel.add(cButton);
setLayout(new FlowLayout());
add(pad);
add(display);
add(buttonPanel);
showState();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

/**
Updates display message.
*/
public void showState()
{
int state = theATM.getState();
pad.clear();
if (state == ATM.START)
display.setText("Enter customer numbernA = OK");
else if (state == ATM.PIN)
display.setText("Enter PINnA = OK");
else if (state == ATM.ACCOUNT)
display.setText("Select Accountn"
+ "A = CheckingnB = SavingsnC = Exit");
else if (state == ATM.TRANSACT)
display.setText("Balance = "
+ theATM.getBalance()
+ "nEnter amount and select transactionn"
+ "A = WithdrawnB = DepositnC = Cancel");
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

class AButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if (state == ATM.START)
theATM.setCustomerNumber((int) pad.getValue());
else if (state == ATM.PIN)
theATM.selectCustomer((int) pad.getValue());
else if (state == ATM.ACCOUNT)
theATM.selectAccount(ATM.CHECKING);
else if (state == ATM.TRANSACT)
{
theATM.withdraw(pad.getValue());
theATM.back();
}
showState();
}
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

class BButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if (state == ATM.ACCOUNT)
theATM.selectAccount(ATM.SAVINGS);
else if (state == ATM.TRANSACT)
{
theATM.deposit(pad.getValue());
theATM.back();
}
showState();
}
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/ATMFrame.java (cont.)
121
122
123
124
125
126
127
128
129
130
131
132
133

class CButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if (state == ATM.ACCOUNT)
theATM.reset();
else if (state == ATM.TRANSACT)
theATM.back();
showState();
}
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/KeyPad.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

import
import
import
import
import
import
import

java.awt.BorderLayout;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JButton;
javax.swing.JPanel;
javax.swing.JTextField;

/**
A component that lets the user enter a number, using
a button pad labeled with digits.
*/
public class KeyPad extends JPanel
{
private JPanel buttonPanel;
private JButton clearButton;
private JTextField display;

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/KeyPad.java (cont.)
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

// Add digit buttons
addButton("7");
addButton("8");
addButton("9");
addButton("4");
addButton("5");
addButton("6");
addButton("1");
addButton("2");
addButton("3");
addButton("0");
addButton(".");
// Add clear entry button
clearButton = new JButton("CE");
buttonPanel.add(clearButton);

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/KeyPad.java (cont.)
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

class ClearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
display.setText("");
}
}
ActionListener listener = new ClearButtonListener();
clearButton.addActionListener(new
ClearButtonListener());
add(buttonPanel, "Center");
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/KeyPad.java (cont.)
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

/**
Adds a button to the button panel
@param label the button label
*/
private void addButton(final String label)
{
class DigitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// Don&apos;t add two decimal points
if (label.equals(".")
&& display.getText().indexOf(".") != -1)
return;
// Append label text to button
display.setText(display.getText() + label);

}
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch12/atm/KeyPad.java (cont.)
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

JButton button = new JButton(label);
buttonPanel.add(button);
ActionListener listener = new DigitButtonListener();
button.addActionListener(listener);
}
/**
Gets the value that the user entered.
@return the value in the text field of the keypad
*/
public double getValue()
{
return Double.parseDouble(display.getText());
}
/**
Clears the display.
*/
public void clear()
{
display.setText("");
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.
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 © 2009 by John Wiley & Sons. All rights reserved.

Weitere ähnliche Inhalte

Was ist angesagt?

Artificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesArtificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesDr. C.V. Suresh Babu
 
Business Models_Internet of Things (Part 01)
Business Models_Internet of Things (Part 01)Business Models_Internet of Things (Part 01)
Business Models_Internet of Things (Part 01)alengadan
 
Component level design
Component level designComponent level design
Component level designNadia Nahar
 
Developing Knowledge-Based Systems
Developing Knowledge-Based SystemsDeveloping Knowledge-Based Systems
Developing Knowledge-Based SystemsAshique Rasool
 
Natural Language Processing in Artificial Intelligence - Codeup #5 - PayU
Natural Language Processing in Artificial Intelligence  - Codeup #5 - PayU Natural Language Processing in Artificial Intelligence  - Codeup #5 - PayU
Natural Language Processing in Artificial Intelligence - Codeup #5 - PayU Artivatic.ai
 
Lec 3 knowledge acquisition representation and inference
Lec 3  knowledge acquisition representation and inferenceLec 3  knowledge acquisition representation and inference
Lec 3 knowledge acquisition representation and inferenceEyob Sisay
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and DesignRiazAhmad786
 
Introduction to internet of things
Introduction to internet of thingsIntroduction to internet of things
Introduction to internet of thingsBhargavi Padmaraju
 

Was ist angesagt? (20)

Intro to Agent-based System
Intro to Agent-based SystemIntro to Agent-based System
Intro to Agent-based System
 
GRASP Principles
GRASP PrinciplesGRASP Principles
GRASP Principles
 
Fuzzy Logic
Fuzzy LogicFuzzy Logic
Fuzzy Logic
 
CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4
 
OS-Part-06.pdf
OS-Part-06.pdfOS-Part-06.pdf
OS-Part-06.pdf
 
Artificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesArtificial Intelligence Searching Techniques
Artificial Intelligence Searching Techniques
 
Threads presentation
Threads presentationThreads presentation
Threads presentation
 
Business Models_Internet of Things (Part 01)
Business Models_Internet of Things (Part 01)Business Models_Internet of Things (Part 01)
Business Models_Internet of Things (Part 01)
 
09 grasp
09 grasp09 grasp
09 grasp
 
Component level design
Component level designComponent level design
Component level design
 
Developing Knowledge-Based Systems
Developing Knowledge-Based SystemsDeveloping Knowledge-Based Systems
Developing Knowledge-Based Systems
 
Ontology engineering
Ontology engineering Ontology engineering
Ontology engineering
 
Natural Language Processing in Artificial Intelligence - Codeup #5 - PayU
Natural Language Processing in Artificial Intelligence  - Codeup #5 - PayU Natural Language Processing in Artificial Intelligence  - Codeup #5 - PayU
Natural Language Processing in Artificial Intelligence - Codeup #5 - PayU
 
Fuzzy expert system
Fuzzy expert systemFuzzy expert system
Fuzzy expert system
 
Lec 3 knowledge acquisition representation and inference
Lec 3  knowledge acquisition representation and inferenceLec 3  knowledge acquisition representation and inference
Lec 3 knowledge acquisition representation and inference
 
Chapter 5 of 1
Chapter 5 of 1Chapter 5 of 1
Chapter 5 of 1
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and Design
 
Internet Of Things (IOT)
Internet Of Things (IOT)Internet Of Things (IOT)
Internet Of Things (IOT)
 
Introduction to internet of things
Introduction to internet of thingsIntroduction to internet of things
Introduction to internet of things
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 

Ähnlich wie Lecture 3 object-oriented design

Software Engineering Methodologies
Software Engineering MethodologiesSoftware Engineering Methodologies
Software Engineering MethodologiesDamian T. Gordon
 
Introduction to Software Engineering and Software Process Models
Introduction to Software Engineering and Software Process ModelsIntroduction to Software Engineering and Software Process Models
Introduction to Software Engineering and Software Process Modelssantoshkawade5
 
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...Adrian Jones
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharpMallikarjuna G D
 
50500113 spiral-model
50500113 spiral-model50500113 spiral-model
50500113 spiral-modelasidharath
 
Final spiralmodel97
Final spiralmodel97Final spiralmodel97
Final spiralmodel97akshay8835
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Scaling a Web Site - OSCON Tutorial
Scaling a Web Site - OSCON TutorialScaling a Web Site - OSCON Tutorial
Scaling a Web Site - OSCON Tutorialduleepa
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practicesBill Buchan
 
It is a sunny day
It is a sunny dayIt is a sunny day
It is a sunny daybcoder
 
Friday final test
Friday final testFriday final test
Friday final testbcoder
 
It's XP Stupid (2019)
It's XP Stupid (2019)It's XP Stupid (2019)
It's XP Stupid (2019)Mike Harris
 
Встреча "QA: в каких направлениях может найти себя тестировщик?"
Встреча "QA: в каких направлениях может найти себя тестировщик?"Встреча "QA: в каких направлениях может найти себя тестировщик?"
Встреча "QA: в каких направлениях может найти себя тестировщик?"GoIT
 
SDLC- concept and models
SDLC- concept and modelsSDLC- concept and models
SDLC- concept and modelsAnjali Arora
 
How To Fit Testing Into The Iteration
How To Fit Testing Into The IterationHow To Fit Testing Into The Iteration
How To Fit Testing Into The IterationRally Software
 
Cleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsCleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsMike Long
 

Ähnlich wie Lecture 3 object-oriented design (20)

Software Engineering Methodologies
Software Engineering MethodologiesSoftware Engineering Methodologies
Software Engineering Methodologies
 
Introduction to Software Engineering and Software Process Models
Introduction to Software Engineering and Software Process ModelsIntroduction to Software Engineering and Software Process Models
Introduction to Software Engineering and Software Process Models
 
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...
The Agile Drupalist - Methodologies & Techniques for Running Effective Drupal...
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharp
 
50500113 spiral-model
50500113 spiral-model50500113 spiral-model
50500113 spiral-model
 
spiralmodel -1
 spiralmodel -1 spiralmodel -1
spiralmodel -1
 
Final spiralmodel97
Final spiralmodel97Final spiralmodel97
Final spiralmodel97
 
Software testing
Software testingSoftware testing
Software testing
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Scaling a Web Site - OSCON Tutorial
Scaling a Web Site - OSCON TutorialScaling a Web Site - OSCON Tutorial
Scaling a Web Site - OSCON Tutorial
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
It is a sunny day
It is a sunny dayIt is a sunny day
It is a sunny day
 
Friday final test
Friday final testFriday final test
Friday final test
 
It's XP Stupid (2019)
It's XP Stupid (2019)It's XP Stupid (2019)
It's XP Stupid (2019)
 
The Waterfall Model
The Waterfall ModelThe Waterfall Model
The Waterfall Model
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 
Встреча "QA: в каких направлениях может найти себя тестировщик?"
Встреча "QA: в каких направлениях может найти себя тестировщик?"Встреча "QA: в каких направлениях может найти себя тестировщик?"
Встреча "QA: в каких направлениях может найти себя тестировщик?"
 
SDLC- concept and models
SDLC- concept and modelsSDLC- concept and models
SDLC- concept and models
 
How To Fit Testing Into The Iteration
How To Fit Testing Into The IterationHow To Fit Testing Into The Iteration
How To Fit Testing Into The Iteration
 
Cleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsCleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy Projects
 

Mehr von Nada G.Youssef

Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Nada G.Youssef
 
Chapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorChapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorNada G.Youssef
 
Chapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsChapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsNada G.Youssef
 
Chapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementChapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementNada G.Youssef
 
Chapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementChapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementNada G.Youssef
 
Chapter 10: Information Systems Acquisition, Development, and Maintenance
			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance
Chapter 10: Information Systems Acquisition, Development, and MaintenanceNada G.Youssef
 
Chapter 9: Access Control Management
Chapter 9: Access Control ManagementChapter 9: Access Control Management
Chapter 9: Access Control ManagementNada G.Youssef
 

Mehr von Nada G.Youssef (20)

مجلة 1
مجلة 1مجلة 1
مجلة 1
 
Chapter Tewlve
Chapter TewlveChapter Tewlve
Chapter Tewlve
 
Chapter Eleven
Chapter ElevenChapter Eleven
Chapter Eleven
 
Chapter Ten
Chapter TenChapter Ten
Chapter Ten
 
Chapter Nine
Chapter NineChapter Nine
Chapter Nine
 
Chapter Eight
Chapter Eight Chapter Eight
Chapter Eight
 
Chapter Seven
Chapter SevenChapter Seven
Chapter Seven
 
Chapter Six
Chapter SixChapter Six
Chapter Six
 
Chapter Five
Chapter FiveChapter Five
Chapter Five
 
Chapter Four
Chapter FourChapter Four
Chapter Four
 
Chapter Three
Chapter ThreeChapter Three
Chapter Three
 
Chapter Two
Chapter TwoChapter Two
Chapter Two
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants
 
Chapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorChapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare Sector
 
Chapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsChapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial Institutions
 
Chapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementChapter 12: Business Continuity Management
Chapter 12: Business Continuity Management
 
Chapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementChapter 11: Information Security Incident Management
Chapter 11: Information Security Incident Management
 
Chapter 10: Information Systems Acquisition, Development, and Maintenance
			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance
Chapter 10: Information Systems Acquisition, Development, and Maintenance
 
Chapter 9: Access Control Management
Chapter 9: Access Control ManagementChapter 9: Access Control Management
Chapter 9: Access Control Management
 

Kürzlich hochgeladen

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Kürzlich hochgeladen (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Lecture 3 object-oriented design

  • 1. Chapter 12 – Object-Oriented Design Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 2. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 3. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 4. Analysis • Decide what the project is supposed 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 5. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 6. Implementation • Write and compile the code • Code implements classes and methods discovered in the design phase • Program Run: Completed program Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 7. Testing • Run tests to verify the program works correctly • Program Run: A report of the tests and their results Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 8. Deployment • Users install program • Users use program for its intended purpose Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 9. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 10. 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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 11. The Spiral Model • Problem: Can lead to many iterations, and process can take too long to complete Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 12. Activity Levels in the Rational Unified Process Development process methodology by the inventors of UML Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 13. Extreme Programming • Strives for simplicity • Removes formal structure • Focuses on best practices Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 14. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 15. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 16. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 17. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 18. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 19. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 20. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 21. Object-Oriented Design 1. Discover classes 2. Determine responsibilities of each class 3. Describe relationships between the classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 22. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 23. Example: Invoice Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 24. Example: Invoice • Classes that come to mind: Invoice, LineItem, 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 25. Finding Classes • Keep the following points in mind: • Class represents set of objects with the same behavior o o o Entities with multiple occurrences in problem description are good candidates for objects Find out what they have in common 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 26. 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 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 27. CRC Card • Indicate what other classes are needed to fulfill responsibility (collaborators) Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 28. Self Check 12.4 Suppose the invoice is to be saved to a file. Name a likely collaborator. Answer: PrintStream Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 29. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 30. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 31. Relationships Between Classes • Inheritance • Aggregation • Dependency Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 32. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 33. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 34. Example class Car extends Vehicle { ... private Tire[] tires; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 35. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 36. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 37. Self Check 12.7 Consider the Bank and BankAccount classes of Chapter 7. How are they related? Answer: Through aggregation. The bank manages bank account objects. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 38. Self Check 12.8 Consider the BankAccount and SavingsAccount objects of Chapter 10. How are they related? Answer: Through inheritance. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 39. Self Check 12.9 Consider the BankAccountTester class of Chapter 3. Which classes does it depend on? Answer: The BankAccount, System, and PrintStream classes. Big Java by Cay Horstmann Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Copyright © 2009 by John Wiley & Sons. All rights reserved. Sons. All rights reserved.
  • 40. Attributes and Methods in UML Diagrams Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 41. Multiplicities • any number (zero or more): * • one or more: 1..* • zero or one: 0..1 • exactly one: 1 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 42. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 43. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 44. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 45. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 46. Case Study: Printing an Invoice — CRC Cards • Discover classes • Nouns are possible classes: Invoice Address LineItem Product Description Price Quantity Total Amount Due Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 47. Case Study: Printing an Invoice — CRC Cards • Analyze classes: Invoice Address LineItem Product Description Price Quantity Total Amount Due // Records the product and the quantity // // // // // variable of the Product class variable of the Product class Not an attribute of a Product Computed – not stored anywhere Computed – not stored anywhere • Classes after a process of elimination: Invoice Address LineItem Product Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 48. CRC Cards for Printing Invoice Invoice and Address must be able to format themselves: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 49. CRC Cards for Printing Invoice Add collaborators to invoice card: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 50. CRC Cards for Printing Invoice Product and LineItem CRC cards: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 51. CRC Cards for Printing Invoice Invoice must be populated with products and quantities: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 52. Printing an Invoice — UML Diagrams Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 53. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 54. 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 aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product aProduct, int quantity) { } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 55. Method Documentation — Invoice Class (cont.) /** Formats the invoice. @return the formatted invoice */ public String format() { } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 56. Method Documentation – LineItem Class /** Describes a quantity of an article to purchase and its price. */ public class LineItem { /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 57. Method Documentation — LineItem Class (cont.) /** Formats this item. @return a formatted string of this line item */ public String format() { } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 58. 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 getDescription() { } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 59. Method Documentation — Product Class (cont.) /** Gets the product price. @return the unit price */ public double getPrice() { } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 60. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 61. The Class Documentation in the HTML Format Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 62. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 63. Implementation • Invoice aggregates Address and LineItem • Every invoice has one billing address • An invoice can have many line items: public class Invoice { ... private Address billingAddress; private ArrayList<LineItem> items; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 64. Implementation A line item needs to store a Product object and quantity: public class LineItem { ... private int quantity; private Product theProduct; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 65. Implementation • The methods themselves are now very easy • Example: • getTotalPrice of LineItem 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 getTotalPrice() { return theProduct.getPrice() * quantity; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 66. ch12/invoice/InvoicePrinter.java 1 2 3 4 5 6 7 8 9 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 InvoicePrinter { public static void main(String[] args) { Address samsAddress = new Address("Sam&apos;s Small Appliances", "100 Main Street", "Anytown", "CA", "98765"); Invoice samsInvoice samsInvoice.add(new samsInvoice.add(new samsInvoice.add(new = new Invoice(samsAddress); Product("Toaster", 29.95), 3); Product("Hair dryer", 24.95), 1); Product("Car vacuum", 19.99), 2); System.out.println(samsInvoice.format()); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 67. ch12/invoice/Invoice.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import java.util.ArrayList; /** Describes an invoice for a set of purchased products. */ public class Invoice { private Address billingAddress; private ArrayList<LineItem> items; /** Constructs an invoice. @param anAddress the billing address */ public Invoice(Address anAddress) { items = new ArrayList<LineItem>(); billingAddress = anAddress; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 68. ch12/invoice/Invoice.java (cont.) 21 22 23 24 25 26 27 28 29 30 31 /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product aProduct, int quantity) { LineItem anItem = new LineItem(aProduct, quantity); items.add(anItem); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 69. ch12/invoice/Invoice.java (cont.) 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /** Formats the invoice. @return the formatted invoice */ public String format() { String r = " I N V O I C Enn" + billingAddress.format() + String.format("nn%-30s%8s%5s%8sn", "Description", "Price", "Qty", "Total"); for (LineItem item : items) { r = r + item.format() + "n"; } r = r + String.format("nAMOUNT DUE: $%8.2f", getAmountDue()); return r; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 70. ch12/invoice/Invoice.java (cont.) 53 54 55 56 57 58 59 60 61 62 63 64 65 66 /** Computes the total amount due. @return the amount due */ public double getAmountDue() { double amountDue = 0; for (LineItem item : items) { amountDue = amountDue + item.getTotalPrice(); } return amountDue; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 71. ch12/invoice/LineItem.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /** Describes a quantity of an article to purchase. */ public class LineItem { private int quantity; private Product theProduct; /** Constructs an item from the product and quantity. @param aProduct the product @param aQuantity the item quantity */ public LineItem(Product aProduct, int aQuantity) { theProduct = aProduct; quantity = aQuantity; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 72. ch12/invoice/LineItem.java (cont.) 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; } /** Formats this item. @return a formatted string of this item */ public String format() { return String.format("%-30s%8.2f%5d%8.2f", theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice()); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 73. ch12/invoice/Product.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /** Describes a product with a description and a price. */ public class Product { private String description; private double price; /** Constructs a product from a description and a price. @param aDescription the product description @param aPrice the product price */ public Product(String aDescription, double aPrice) { description = aDescription; price = aPrice; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 74. ch12/invoice/Product.java (cont.) 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 /** Gets the product description. @return the description */ public String getDescription() { return description; } /** Gets the product price. @return the unit price */ public double getPrice() { return price; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 75. ch12/invoice/Address.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /** Describes a mailing address. */ public class Address { private String name; private String street; private String city; private String state; private String zip; /** Constructs a mailing address. @param aName the recipient name @param aStreet the street @param aCity the city @param aState the two-letter state code @param aZip the ZIP postal code */ Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 76. ch12/invoice/Address.java (cont.) 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public Address(String aName, String aStreet, String aCity, String aState, String aZip) { name = aName; street = aStreet; city = aCity; state = aState; zip = aZip; } /** Formats the address. @return the address as a string with three lines */ public String format() { return name + "n" + street + "n" + city + ", " + state + " " + zip; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 77. 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 LineItem class. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 78. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 79. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 80. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 81. Case Study: An Automatic Teller Machine — Requirements • Two separate interfaces: • GUI that closely mimics an actual ATM • Text-based interface Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 82. Case Study: An Automatic Teller Machine — Requirements • GUI Interface • Keypad • Display • Buttons A, B, C • Button functions depend on the state of the machine Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 83. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 84. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 85. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 86. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 87. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 88. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 89. Case Study: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 90. An Automatic Teller Machine – CRC Cards Nouns are possible classes: ATM User Keypad Display Display message Button State Bank account Checking account Savings account Customer Customer number PIN Bank Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 91. CRC Cards for Automatic Teller Machine Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 92. CRC Cards for Automatic Teller Machine Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 93. ATM States 1. START: Enter customer ID 2. PIN: Enter PIN 3. ACCOUNT: Select account 4. TRANSACT: Select transaction Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 94. State Diagram for ATM Class Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 95. An Automatic Teller Machine – UML Diagrams Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 96. Method Documentation ATM Class /** An ATM that accesses a bank. */ public class ATM { /** Constructs an ATM for a given bank. @param aBank the bank to which this ATM connects */ public ATM(Bank aBank) { } /** Sets the current customer number and sets state to PIN. (Precondition: state is START) @param number the customer number */ public void setCustomerNumber(int number) { } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 97. Method Documentation ATM Class (cont.) /** 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 selectCustomer(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 © 2009 by John Wiley & Sons. All rights reserved.
  • 98. Method Documentation ATM Class (cont.) public void selectAccount(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 © 2009 by John Wiley & Sons. All rights reserved.
  • 99. An Automatic Teller Machine — Implementation • Start implementation with classes that don’t depend on others • Keypad • BankAccount • Then implement Customer which depends only on BankAccount • This bottom-up approach allows you to test your classes individually Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 100. An Automatic Teller Machine — Implementation • Aggregated classes in UML diagram give instance variables public class ATM { private Bank theBank; ... } • From description of ATM states, it is clear that we require additional instance variables: public class ATM { private int state; private Customer currentCustomer; private BankAccount currentAccount; ... } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 101. An Automatic Teller Machine — Implementation • Most methods are very straightforward to implement • Consider selectCustomer: /** 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 102. An Automatic Teller Machine — Implementation (cont.) • Description can be almost literally translated to Java instructions: public void selectCustomer(int pin) { assert state == PIN; currentCustomer = theBank.findCustomer(customerNumber, pin); if (currentCustomer == null) state = START; else state = ACCOUNT; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 103. ch12/atm/ATM.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /** An ATM that accesses a bank. */ public class ATM { public static final int CHECKING = 1; public static final int SAVINGS = 2; private private private private private public public public public int state; int customerNumber; Customer currentCustomer; BankAccount currentAccount; Bank theBank; static static static static final final final final int int int int START = 1; PIN = 2; ACCOUNT = 3; TRANSACT = 4; Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 104. ch12/atm/ATM.java (cont.) 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 /** Constructs an ATM for a given bank. @param aBank the bank to which this ATM connects */ public ATM(Bank aBank) { theBank = aBank; reset(); } /** Resets the ATM to the initial state. */ public void reset() { customerNumber = -1; currentAccount = null; state = START; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 105. ch12/atm/ATM.java (cont.) 40 41 42 43 44 45 46 47 48 49 50 51 52 /** Sets the current customer number and sets state to PIN. (Precondition: state is START) @param number the customer number. */ public void setCustomerNumber(int number) { assert state == START; customerNumber = number; state = PIN; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 106. ch12/atm/ATM.java (cont.) 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 /** 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 selectCustomer(int pin) { assert state == PIN; currentCustomer = theBank.findCustomer(customerNumber, pin); if (currentCustomer == null) state = START; else state = ACCOUNT; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 107. ch12/atm/ATM.java (cont.) 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 /** Sets current account to checking or savings. Sets state to TRANSACT. (Precondition: state is ACCOUNT or TRANSACT) @param account one of CHECKING or SAVINGS */ public void selectAccount(int account) { assert state == ACCOUNT || state == TRANSACT; if (account == CHECKING) currentAccount = currentCustomer.getCheckingAccount(); else currentAccount = currentCustomer.getSavingsAccount(); state = TRANSACT; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 108. ch12/atm/ATM.java (cont.) 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 /** Withdraws amount from current account. (Precondition: state is TRANSACT) @param value the amount to withdraw */ public void withdraw(double value) { assert state == TRANSACT; currentAccount.withdraw(value); } /** Deposits amount to current account. (Precondition: state is TRANSACT) @param value the amount to deposit */ public void deposit(double value) { assert state == TRANSACT; currentAccount.deposit(value); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 109. ch12/atm/ATM.java (cont.) 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 /** Gets the balance of the current account. (Precondition: state is TRANSACT) @return the balance */ public double getBalance() { assert state == TRANSACT; return currentAccount.getBalance(); } /** 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; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 110. ch12/atm/ATM.java (cont.) 131 132 133 134 135 136 137 138 139 /** Gets the current state of this ATM. @return the current state */ public int getState() { return state; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 111. ch12/atm/Bank.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import import import import java.io.File; java.io.IOException; java.util.ArrayList; java.util.Scanner; /** A bank contains customers with bank accounts. */ public class Bank { private ArrayList<Customer> customers; /** Constructs a bank with no customers. */ public Bank() { customers = new ArrayList<Customer>(); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 112. ch12/atm/Bank.java (cont.) 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 /** Reads the customer numbers and pins and initializes the bank accounts. @param filename the name of the customer file */ public void readCustomers(String filename) throws IOException { Scanner in = new Scanner(new File(filename)); while (in.hasNext()) { int number = in.nextInt(); int pin = in.nextInt(); Customer c = new Customer(number, pin); addCustomer(c); } in.close(); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 113. ch12/atm/Bank.java (cont.) 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 /** Adds a customer to the bank. @param c the customer to add */ public void addCustomer(Customer c) { customers.add(c); } /** Finds a customer in the bank. @param aNumber a customer number @param aPin a personal identification number @return the matching customer, or null if no customer matches */ public Customer findCustomer(int aNumber, int aPin) { for (Customer c : customers) { if (c.match(aNumber, aPin)) return c; } return null; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 114. ch12/atm/Customer.java 1 2 3 4 5 6 7 8 9 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 { private int customerNumber; private int pin; private BankAccount checkingAccount; private BankAccount savingsAccount; /** Constructs a customer with a given number and PIN. @param aNumber the customer number @param aPin the personal identification number */ public Customer(int aNumber, int aPin) { customerNumber = aNumber; pin = aPin; checkingAccount = new BankAccount(); savingsAccount = new BankAccount(); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 115. ch12/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 /** Tests if this customer matches a customer number and PIN. @param aNumber a customer number @param aPin a personal identification number @return true if the customer number and PIN match */ public boolean match(int aNumber, int aPin) { return customerNumber == aNumber && pin == aPin; } /** Gets the checking account of this customer. @return the checking account */ public BankAccount getCheckingAccount() { return checkingAccount; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 116. ch12/atm/Customer.java (cont.) 45 46 47 48 49 50 51 52 53 /** Gets the savings account of this customer. @return the checking account */ public BankAccount getSavingsAccount() { return savingsAccount; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 117. ch12/atm/ATMSimulator.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 theATM; try { Bank theBank = new Bank(); theBank.readCustomers("customers.txt"); theATM = new ATM(theBank); } catch(IOException e) { System.out.println("Error opening accounts file."); return; Continued } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 118. ch12/atm/ATMSimulator.java (cont.) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Scanner in = new Scanner(System.in); while (true) { int state = theATM.getState(); if (state == ATM.START) { System.out.print("Enter customer number: "); int number = in.nextInt(); theATM.setCustomerNumber(number); } else if (state == ATM.PIN) { System.out.print("Enter PIN: "); int pin = in.nextInt(); theATM.selectCustomer(pin); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 119. ch12/atm/ATMSimulator.java (cont.) 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 else if (state == ATM.ACCOUNT) { System.out.print("A=Checking, B=Savings, C=Quit: "); String command = in.next(); if (command.equalsIgnoreCase("A")) theATM.selectAccount(ATM.CHECKING); else if (command.equalsIgnoreCase("B")) theATM.selectAccount(ATM.SAVINGS); else if (command.equalsIgnoreCase("C")) theATM.reset(); else System.out.println("Illegal input!"); } else if (state == ATM.TRANSACT) { System.out.println("Balance=" + theATM.getBalance()); System.out.print("A=Deposit, B=Withdrawal, C=Cancel: "); String command = in.next(); Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 120. ch12/atm/ATMSimulator.java (cont.) 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 if (command.equalsIgnoreCase("A")) { System.out.print("Amount: "); double amount = in.nextDouble(); theATM.deposit(amount); theATM.back(); } else if (command.equalsIgnoreCase("B")) { System.out.print("Amount: "); double amount = in.nextDouble(); theATM.withdraw(amount); theATM.back(); } else if (command.equalsIgnoreCase("C")) theATM.back(); else System.out.println("Illegal input!"); } } } } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 121. ch12/atm/ATMSimulator.java (cont.) Program Run: 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 122. ch12/atm/ATMViewer.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.io.IOException; import javax.swing.JFrame; import javax.swing.JOptionPane; /** A graphical simulation of an automatic teller machine. */ public class ATMViewer { public static void main(String[] args) { ATM theATM; try { Bank theBank = new Bank(); theBank.readCustomers("customers.txt"); theATM = new ATM(theBank); } catch(IOException e) { JOptionPane.showMessageDialog(null, "Error opening accounts file."); return; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 123. ch12/atm/ATMViewer.java (cont.) 26 27 28 29 30 31 32 JFrame frame = new ATMFrame(theATM); frame.setTitle("First National Bank of Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 124. ch12/atm/ATMFrame.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import import import import import import import import java.awt.FlowLayout; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JPanel; javax.swing.JTextArea; /** A frame displaying the components of an ATM. */ public class ATMFrame extends JFrame { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 300; private JButton aButton; private JButton bButton; private JButton cButton; private KeyPad pad; private JTextArea display; Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 125. ch12/atm/ATMFrame.java (cont.) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 private ATM theATM; /** Constructs the user interface of the ATM frame. */ public ATMFrame(ATM anATM) { theATM = anATM; // Construct components pad = new KeyPad(); display = new JTextArea(4, 20); aButton = new JButton(" A "); aButton.addActionListener(new AButtonListener()); bButton = new JButton(" B "); bButton.addActionListener(new BButtonListener()); Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 126. ch12/atm/ATMFrame.java (cont.) 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 cButton = new JButton(" C "); cButton.addActionListener(new CButtonListener()); // Add components JPanel buttonPanel = new JPanel(); buttonPanel.add(aButton); buttonPanel.add(bButton); buttonPanel.add(cButton); setLayout(new FlowLayout()); add(pad); add(display); add(buttonPanel); showState(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 127. ch12/atm/ATMFrame.java (cont.) 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 /** Updates display message. */ public void showState() { int state = theATM.getState(); pad.clear(); if (state == ATM.START) display.setText("Enter customer numbernA = OK"); else if (state == ATM.PIN) display.setText("Enter PINnA = OK"); else if (state == ATM.ACCOUNT) display.setText("Select Accountn" + "A = CheckingnB = SavingsnC = Exit"); else if (state == ATM.TRANSACT) display.setText("Balance = " + theATM.getBalance() + "nEnter amount and select transactionn" + "A = WithdrawnB = DepositnC = Cancel"); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 128. ch12/atm/ATMFrame.java (cont.) 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 class AButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.START) theATM.setCustomerNumber((int) pad.getValue()); else if (state == ATM.PIN) theATM.selectCustomer((int) pad.getValue()); else if (state == ATM.ACCOUNT) theATM.selectAccount(ATM.CHECKING); else if (state == ATM.TRANSACT) { theATM.withdraw(pad.getValue()); theATM.back(); } showState(); } } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 129. ch12/atm/ATMFrame.java (cont.) 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 class BButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.ACCOUNT) theATM.selectAccount(ATM.SAVINGS); else if (state == ATM.TRANSACT) { theATM.deposit(pad.getValue()); theATM.back(); } showState(); } } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 130. ch12/atm/ATMFrame.java (cont.) 121 122 123 124 125 126 127 128 129 130 131 132 133 class CButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.ACCOUNT) theATM.reset(); else if (state == ATM.TRANSACT) theATM.back(); showState(); } } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 131. ch12/atm/KeyPad.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import import import import import import import java.awt.BorderLayout; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JPanel; javax.swing.JTextField; /** A component that lets the user enter a number, using a button pad labeled with digits. */ public class KeyPad extends JPanel { private JPanel buttonPanel; private JButton clearButton; private JTextField display; Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 132. ch12/atm/KeyPad.java (cont.) 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 // Add digit buttons addButton("7"); addButton("8"); addButton("9"); addButton("4"); addButton("5"); addButton("6"); addButton("1"); addButton("2"); addButton("3"); addButton("0"); addButton("."); // Add clear entry button clearButton = new JButton("CE"); buttonPanel.add(clearButton); Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 133. ch12/atm/KeyPad.java (cont.) 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 class ClearButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { display.setText(""); } } ActionListener listener = new ClearButtonListener(); clearButton.addActionListener(new ClearButtonListener()); add(buttonPanel, "Center"); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 134. ch12/atm/KeyPad.java (cont.) 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 /** Adds a button to the button panel @param label the button label */ private void addButton(final String label) { class DigitButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Don&apos;t add two decimal points if (label.equals(".") && display.getText().indexOf(".") != -1) return; // Append label text to button display.setText(display.getText() + label); } } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 135. ch12/atm/KeyPad.java (cont.) 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 JButton button = new JButton(label); buttonPanel.add(button); ActionListener listener = new DigitButtonListener(); button.addActionListener(listener); } /** Gets the value that the user entered. @return the value in the text field of the keypad */ public double getValue() { return Double.parseDouble(display.getText()); } /** Clears the display. */ public void clear() { display.setText(""); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 136. 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 © 2009 by John Wiley & Sons. All rights reserved.
  • 137. 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 © 2009 by John Wiley & Sons. All rights reserved.