CHAPTER 12
OBJECT-
ORIENTED
DESIGN
Copyright © 2013 by John Wiley & Sons. All rights reserved. Slides by Rick Giles
Chapter Goals
To learn how to discover new classes and
methods
To use CRC cards for class discovery
To understand the concepts of cohesion and
coupling
To identify inheritance, aggregation, and
dependency relationships between classes
To describe class relationships using UML class
diagrams
To apply object-oriented design techniques to
building complex programs
To use packages to organize programs
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 2
12.1 Classes and Their Responsibilities (1)
To discover classes, look for nouns in the
problem description
Example: Print an invoice
Candidate classes:
• Invoice
• LineItem
• Customer
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 3
12.1 Classes and Their Responsibilities (2)
Concepts from the problem domain are
good candidates for classes
Examples:
• From science: Cannonball
• From business: CashRegister
• From a game: Monster
The name for such a class should be a
noun that describes the class
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 4
The CRC Card Method
A CRC card describes a class, its
responsibilities, and its collaborating
classes.
For each responsibility of a class, its
collaborators are the other classes needed to
fulfill it
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 5
CRC Card
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 6
Cohesion (1)
A class should represent a single concept
The public interface of a class is cohesive
if all of its features are related to the
concept that the class represents
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 7
Cohesion (2)
This class lacks cohesion:
public class CashRegister
{
public static final double NICKEL_VALUE = 0.05;
public static final double DIME_VALUE = 0.1;
public static final double QUARTER_VALUE = 0.25;
…
public void enterPayment(int dollars, int quarters,
int dimes, int nickels, int pennies)
. . .
}
It involves two concepts: cash register and
coin
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 8
Cohesion (3)
Better: Make two classes:
public class Coin
{
public Coin(double aValue, String aName) { . . . }
public double getValue() { . . . }
. . .
}
public class CashRegister
{
public void enterPayment(int coinCount, Coin coinType)
{ . . . }
. . .
}
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 9
12.2 Relationships Between Classes
A class depends on another if it uses
objects of that class
• “knows about” relationship
CashRegister depends on Coin to
determine the value of the payment
To visualize relationships, draw class
diagrams
UML: Unified Modeling Language
• Notation for object-oriented analysis and design
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 10
Dependency Relationship
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 11
Coupling (1)
If many classes depend on each other, the
coupling between classes is high
Good practice: minimize coupling between
classes
Change in one class may require update of all
coupled classes
Using a class in another program requires
using all classes on which it depends
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 12
Coupling (2)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 13
Aggregation (1)
A class aggregates another of its objects
contain objects of another class
“has-a” relationship
Example: a quiz is made up of questions
Class Quiz aggregates class Question
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 14
Aggregation (2)
Finding out about aggregation helps in
implementing classes
Example: since a quiz can have any
number of questions, use an array or array
list for collecting them
public class Quiz
{
private ArrayList<Question> questions;
. . .
}
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 15
Inheritance (1)
Inheritance is the relationship between a
more general class (superclass) and a
more specialized class (subclass)
“is-a” relationship
Example: every car is a vehicle; every car
has tires
Class Car is a subclass of class Vehicle; class
car aggregates class Tire
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 16
Inheritance (2)
public class Car extends Vehicle
{
private Tire[] tires;
. . .
}
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 17
UML Relationship Symbols
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 18
Parallel Arrays (1)
Parallel arrays have the same length, each
of which stores a part of what conceptually
should be an object
Example:
String[] descriptions;
double[] prices;
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 19
Parallel Arrays (2)
Programmer must ensure arrays always
have the same length and that each slice is
filled with values that belong together
Any method that operates on a slice must
get all values of the slice as parameters
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 20
Parallel Arrays (3)
Avoid parallel arrays by changing them into
an array of objects
Example:
public class Item
{
private String description;
private double price;
}
Replace parallel arrays with
Item[] items;
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 21
Parallel Arrays (4)
Each slot in the resulting array corresponds
to a slice in the set of parallel arrays
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 22
12.3 Application: Printing an Invoice
Five-part development process:
1. Gather requirements.
2. Use CRC cards to find classes,
responsibilities, collaborators.
3. Use UML diagrams to record relationships.
4. Use javadoc to document method behavior.
5. Implement your program.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 23
Requirements
Program prints the billing address, all line
items, and the amount due
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 24
CRC Cards (1)
Nouns from requirements:
Invoice Product
LineItem Price
Description Total
Quantity
Amount due
Address
Description and Price are attributes of the
Product class
Quantity is an attribute of the LineItem class
Total and Amount due are computed
Copyright © 2011 by John Wiley & Sons. All rights reserved. Page 25
CRC Cards (2)
Left with four candidate classes:
Invoice
Address
LineItem
Product
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 26
CRC Cards (3)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 27
UML Class Diagram
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 28
Method Documentation (1)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 29
Method Documentation (2)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 30
Method Documentation (3)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 31
Method Documentation (4)
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 32
Class Documentation in HTML Format
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 33
[Link]
1 /**
2 This program demonstrates the invoice classes by printing
3 a sample invoice.
4 */
5 public class InvoicePrinter
6 {
7 public static void main(String[] args)
8 {
9 Address samsAddress
10 = new Address("Sam's Small Appliances",
11 "100 Main Street", "Anytown", "CA", "98765");
12
13 Invoice samsInvoice = new Invoice(samsAddress);
14 [Link](new Product("Toaster", 29.95), 3);
15 [Link](new Product("Hair dryer", 24.95), 1);
16 [Link](new Product("Car vacuum", 19.99), 2);
17
18 [Link]([Link]());
19 }
20 }
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 34
[Link]
1 import [Link];
2
3 /**
4 Describes an invoice for a set of purchased products.
5 */
6 public class Invoice
7 {
8 private Address billingAddress;
9 private ArrayList<LineItem> items;
10
11 /**
12 Constructs an invoice.
13 @param anAddress the billing address
14 */
15 public Invoice(Address anAddress)
16 {
17 items = new ArrayList<LineItem>();
18 billingAddress = anAddress;
19 }
20
Continued
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 35
[Link] (cont.)
21 /**
22 Adds a charge for a product to this invoice.
23 @param aProduct the product that the customer ordered
24 @param quantity the quantity of the product
25 */
26 public void add(Product aProduct, int quantity)
27 {
28 LineItem anItem = new LineItem(aProduct, quantity);
29 [Link](anItem);
30 }
31
Continued
Copyright © 2013 John Wiley & Sons. All rights reserved. Page 36
[Link] (cont.)
32 /**
33 Formats the invoice.
34 @return the formatted invoice
35 */
36 public String format()
37 {
38 String r = " I N V O I C E\n\n"
39 + [Link]()
40 + [Link]("\n\n%-30s%8s%5s%8s\n",
41 "Description", "Price", "Qty", "Total");
42
43 for (LineItem item : items)
44 {
45 r = r + [Link]() + "\n";
46 }
47
48 r = r + [Link]("\nAMOUNT DUE: $%8.2f", getAmountDue());
49
50 return r;
51 }
52
Continued
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 37
[Link] (cont.)
53 /**
54 Computes the total amount due.
55 @return the amount due
56 */
57 public double getAmountDue()
58 {
59 double amountDue = 0;
60 for (LineItem item : items)
61 {
62 amountDue = amountDue + [Link]();
63 }
64 return amountDue;
65 }
66 }
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 38
[Link]
1 /**
2 Describes a quantity of an article to purchase.
3 */
4 public class LineItem
5 {
6 private int quantity;
7 private Product theProduct;
8
9 /**
10 Constructs an item from the product and quantity.
11 @param aProduct the product
12 @param aQuantity the item quantity
13 */
14 public LineItem(Product aProduct, int aQuantity)
15 {
16 theProduct = aProduct;
17 quantity = aQuantity;
18 }
19
Continued
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 39
[Link] (cont.)
20 /**
21 Computes the total cost of this line item.
22 @return the total price
23 */
24 public double getTotalPrice()
25 {
26 return [Link]() * quantity;
27 }
28
29 /**
30 Formats this item.
31 @return a formatted string of this item
32 */
33 public String format()
34 {
35 return [Link]("%-30s%8.2f%5d%8.2f",
36 [Link](), [Link](),
37 quantity, getTotalPrice());
38 }
39 }
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 40
[Link]
1 /**
2 Describes a product with a description and a price.
3 */
4 public class Product
5 {
6 private String description;
7 private double price;
8
9 /**
10 Constructs a product from a description and a price.
11 @param aDescription the product description
12 @param aPrice the product price
13 */
14 public Product(String aDescription, double aPrice)
15 {
16 description = aDescription;
17 price = aPrice;
18 }
19
Continued
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 41
[Link] (cont.)
20 /**
21 Gets the product description.
22 @return the description
23 */
24 public String getDescription()
25 {
26 return description;
27 }
28
29 /**
30 Gets the product price.
31 @return the unit price
32 */
33 public double getPrice()
34 {
35 return price;
36 }
37 }
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 42
[Link]
1 /**
2 Describes a mailing address.
3 */
4 public class Address
5 {
6 private String name;
7 private String street;
8 private String city;
9 private String state;
10 private String zip;
11
12 /**
13 Constructs a mailing address.
14 @param aName the recipient name
15 @param aStreet the street
16 @param aCity the city
17 @param aState the two-letter state code
18 @param aZip the ZIP postal code
19 */
Continued
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 43
[Link] (cont.)
20 public Address(String aName, String aStreet,
21 String aCity, String aState, String aZip)
22 {
23 name = aName;
24 street = aStreet;
25 city = aCity;
26 state = aState;
27 zip = aZip;
28 }
29
30 /**
31 Formats the address.
32 @return the address as a string with three lines
33 */
34 public String format()
35 {
36 return name + "\n" + street + "\n"
37 + city + ", " + state + " " + zip;
38 }
39 }
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 44
12.4 Packages
Package: a set of related classes
Important packages in the Java library:
Package Purpose Sample Class
[Link] Language support Math
[Link] Utilities Random
[Link] Input and output PrintStream
[Link] Abstract Windowing Toolkit Color
[Link] Applets Applet
[Link] Networking Socket
[Link] Database Access ResultSet
[Link] Swing user interface JButton
[Link]
Document Object Model for XML Document
documents
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 45
Organizing Related Classes into Packages (1)
To put a class in a package, you must place
package packageName;
as the first statement in its source
Package name consists of one or more
identifiers separated by periods
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 46
Organizing Related Classes into Packages (2)
For example, to put the BankAccount class into a
package named [Link], the [Link]
file must start as follows:
package [Link];
public class BankAccount
{
. . .
}
Default package has no name, no package statement
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 47
Importing Packages
Can always use class without importing:
[Link] in = new [Link]([Link]);
Tedious to use fully qualified name
Import lets you use shorter class name:
import [Link];
...
Scanner in = new Scanner([Link]);
Can import all classes in a package:
import [Link].*;
Never need to import classes in package [Link]
Don’t need to import other classes in the same package
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 48
Package Names
Use packages to avoid name clashes
[Link]
vs.
[Link]
Package names should be unambiguous
Recommendation: start with reversed domain name:
[Link]
[Link]: for Britney Walters’ classes
(walters@[Link])
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 49
How Classes Are Located
Base directory: holds your program's source files
Path of a class source file, relative to base directory, must
match its package name
Example: if base directory is
/home/britney/assignments
place source files for classes in package problem1 in directory
/homehome/britney/assignments/problem1
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 50
Summary
Discover Classes and their Responsibilities
To discover classes, look for nouns in the problem
description.
Concepts from the problem domain are good candidates for
classes.
A CRC card describes a class, its responsibilities, and its
collaborating classes
The public interface of a class is cohesive if all of its features
are related to the concept that the class represents.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 51
Summary
Class Relationships and UML Diagrams
A class depends on another class if it uses objects of that
class.
It is a good practice to minimize the coupling (i.e.,
dependency) between classes.
A class aggregates another if its objects contain objects of
the other class.
Inheritance (the is-a relationship) is sometimes
inappropriately used when the has-a relationship would be
more appropriate.
Aggregation (the has-a relationship) denotes that objects of
one class contain references to objects of another class.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 52
Summary
You need to be able to distinguish the UML notations for
inheritance, interface implementation, aggregation, and
dependency.
Avoid parallel arrays by changing them into arrays of objects.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 53
Summary
Object-Oriented Development Process
Start the development process by gathering and
documenting program requirements.
Use CRC cards to find classes, responsibilities, and
collaborators.
Use UML diagrams to record class relationships.
Use javadoc comments (with the method bodies left blank)
to record the behavior of classes.
After completing the design, implement your classes.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 54
Summary
Packages
A package is a set of related classes.
Use packages to structure the classes in your program.
The import directive lets you refer to a class from a
package by its class name, without the package prefix.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 55