SlideShare a Scribd company logo
1 of 70
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 12 – Object-Oriented Design
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To learn how to discover new classes and methods
 To use CRC cards for class discovery
 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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Discovering Classes
 When designing a program, you work from a requirements
specification
• The designer’s task is to discover structures that make it possible to
implement the requirements
 To discover classes, look for nouns in the problem description.
 Find methods by looking for verbs in the task description.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Example: Invoice
Figure 1 An Invoice
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Example: Invoice
 Classes that come to mind:
• Invoice
• LineItem
• Customer
 Good idea to keep a list of candidate classes.
 Brainstorm: put all ideas for classes onto the list.
 Cross not useful ones later.
 Concepts from the problem domain are good candidates for
classes.
 Not all classes can be discovered from the program
requirements:
• Most programs need tactical classes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
The CRC Card Method
In a class scheduling system,
potential classes from the
problem domain include Class,
LectureHall, Instructor, and
Student.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
The CRC Card Method
 After you have a set of classes
• Define the behavior (methods) of each class
 Look for verbs in the task description
• Match the verbs to the appropriate objects
 The invoice program needs to compute the amount due
• Which class is responsible for this method?
o Invoice class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
The CRC Card Method
 To find the class responsibilities, use the CRC card method.
 A CRC card describes a class, its responsibilities, and its
collaborating classes.
• CRC - stands for “classes”, “responsibilities”, “collaborators”
 Use an index card for each class.
 Pick the class that should be responsible for each method
(verb).
 Write the responsibility onto the class card.
 Indicate what other classes are needed to fulfill responsibility
(collaborators).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
The CRC Card Method
Figure 2 A CRC Card
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Self Check 12.1
Answer: Look for nouns in the problem description.
What is the rule of thumb for finding classes?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Self Check 12.2
Answer: Yes (ChessBoard) and no (MovePiece).
Your job is to write a program that plays chess. Might
ChessBoard be an appropriate class? How about MovePiece?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Self Check 12.3
Answer: PrintStream
Suppose the invoice is to be saved to a file. Name a likely
collaborator.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Self Check 12.4
Answer: To produce the shipping address of the customer.
Looking at the invoice in Figure 1, what is a likely responsibility
of the Customer class?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Self Check 12.5
Answer: Reword the responsibilities so that they are at a
higher level, or come up with more classes to handle the
responsibilities.
What do you do if a CRC card has ten responsibilities?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Relationships Between Classes
The most common types of relationships:
 Dependency
 Aggregation
 Inheritance
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
Dependency
 A class depends on another class if it uses objects of that class.
The “knows about” relationship.
 Example: CashRegister depends on Coin
Figure 3 Dependency Relationship Between the CashRegister
and Coin Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
Dependency
 It is a good practice to minimize the coupling (i.e., dependency)
between classes.
 When a class changes, coupled classes may also need
updating.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Aggregation
 A class aggregates another if its objects contain objects of the
other class.
• Has-a relationship
 Example: a Quiz class aggregates a Question class.
 The UML for aggregation:
 Aggregation is a stronger form of dependency.
 Use aggregation to remember another object between method
calls.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Aggregation
 Use an instance variable
public class Quiz
{
private ArrayList<Question> questions;
. . .
}
 A class may use the Scanner class without ever declaring an
instance variable of class Scanner. This is dependency NOT
aggregation
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Aggregation
A car has a motor and tires. In
object-oriented design, this
“has-a” relationship is called
aggregation.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Inheritance
 Inheritance is a relationship between a more general class (the
superclass) and a more specialized class (the subclass).
• The “is-a” relationship.
• Example: Every truck is a vehicle.
 Inheritance is sometimes inappropriately used when the has-a
relationship would be more appropriate.
• Should the class Tire be a subclass of a class Circle? No
• A tire has a circle as its boundary
• Use aggregation
public class Tire
{
private String rating;
private Circle boundary;
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Inheritance
 Every car is a vehicle. (Inheritance)
 Every car has a tire (or four). (Aggregation)
class Car extends Vehicle
{
private Tire[] tires;
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Inheritance
 Aggregation denotes that objects of one class contain
references to objects of another class.
Figure 6 UML Notation for Inheritance and Aggregation
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
UML Relationship Symbols
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Self Check 12.6
Answer: The CashRegisterTester class depends on the
CashRegister, Coin, and System classes.
Consider the CashRegisterTester class of Section 8.2. On
which classes does it depend?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Self Check 12.7
Answer: The ChoiceQuestion class inherits from the
Question class.
Consider the Question and ChoiceQuestion objects of Chapter
9. How are they related?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Self Check 12.8
Answer: The Quiz class depends on the Question class but
probably not ChoiceQuestion, if we assume that the
methods of the Quiz class manipulate generic Question
objects, as they did in Chapter 9.
Consider the Quiz class described in Section 12.2.2. Suppose
a quiz contains a mixture of Question and ChoiceQuestion
objects. Which classes does the Quiz class depend on?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Self Check 12.9
Answer: If a class doesn’t depend on another, it is not
affected by interface changes in the other class.
Why should coupling be minimized between classes?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Self Check 12.10
Answer:
In an e-mail system, messages are stored in a mailbox. Draw a
UML diagram that shows the appropriate aggregation
relationship.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Self Check 12.11
Answer: Typically, a library system wants to track which books a
patron has checked out, so it makes more sense to have Patron
aggregate Book. However, there is not always one true answer
in design. If you feel strongly that it is important to identify the
patron who checked out a particular book (perhaps to notify the
patron to return it because it was requested by someone else),
then you can argue that the aggregation should go the other
way around.
You are implementing a system to manage a library, keeping
track of which books are checked out by whom. Should the
Book class aggregate Patron or the other way around?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Self Check 12.12
Answer: There would be no relationship.
In a library management system, what would be the
relationship between classes Patron and Author?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Attributes and Methods in UML Diagrams
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Multiplicities
 any number (zero or more): *
 one or more: 1..*
 zero or one: 0..1
 exactly one: 1
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Aggregation and Association, and Composition
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Aggregation and Association, and Composition
 Composition: one of the classes can not exist without the other.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Application: Printing an Invoice
Five-part program 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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Application: Printing an Invoice - Requirements
 Start the development process by gathering and documenting
program 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
Application: Printing an Invoice
Sample Invoice
I N V O I C E
Sam's Small Appliances
100 Main Street
Anytown, CA 98765
Description Price Qty Total
Toaster 29.95 3 89.85
Hair dryer 24.95 1 24.95
Car vacuum 19.99 2 39.98
AMOUNT DUE: $154.78
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
Application: Printing an Invoice
An invoice lists the charges for each item and the amount due.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Application: Printing an Invoice – CRC Cards
 Use CRC cards to find classes, responsibilities, and
collaborators.
 Discover classes
 Nouns are possible classes:
Invoice
Address
LineItem
Product
Description
Price
Quantity
Total
Amount
Due
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
Application: Printing an Invoice – CRC Cards
 Analyze classes:
Invoice
Address
LineItem // Records the product and the quantity
Product
Description // Field of the Product class
Price // Field of the Product class
Quantity // Not an attribute of a Product
Total // Computed - not stored anywhere
Amount Due // Computed - not stored anywhere
 Classes after a process of elimination:
Invoice
Address
LineItem
Product
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
CRC Cards for Printing Invoice
Invoice and Address must be able to format themselves:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
CRC Cards for Printing Invoice
Add collaborators to Invoice card:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
CRC Cards for Printing Invoice
Product and LineItem CRC cards:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
CRC Cards for Printing Invoice
Invoice must be populated with products and quantities:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Application: Printing an Invoice – UML Diagrams
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Printing an Invoice — Method Documentation
 Use javadoc comments (with the method bodies left blank) to
record the behavior of the classes.
 Write a Java source file for each class:
• Write the method comments for those methods that you have
discovered,
• 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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
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)
{
}
/**
Formats the invoice.
@return the formatted invoice
*/
public String format()
{
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
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()
{
}
/**
Formats this item.
@return a formatted string of this line item
*/
public String format()
{
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
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()
{
}
/**
Gets the product price.
@return the unit price
*/
public double getPrice()
{
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
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()
{
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
The Class Documentation in the HTML Format
Figure 8 Class Documentation in HTML Format
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Printing an Invoice — Implementation
 After completing the design, implement your classes.
 The UML diagram will give instance variables:
• Look for aggregated classes
• They yield instance variables
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
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;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Implementation
 A line item needs to store a Product object and quantity:
public class LineItem
{
. . .
private int quantity;
private Product theProduct;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
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;
}
 Also supply constructors
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
section_3/InvoicePrinter.java
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&apos;s Small Appliances",
11 "100 Main Street", "Anytown", "CA", "98765");
12
13 Invoice samsInvoice = new Invoice(samsAddress);
14 samsInvoice.add(new Product("Toaster", 29.95), 3);
15 samsInvoice.add(new Product("Hair dryer", 24.95), 1);
16 samsInvoice.add(new Product("Car vacuum", 19.99), 2);
17
18 System.out.println(samsInvoice.format());
19 }
20 }
21
22
23
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
section_3/Invoice.java
1 import java.util.ArrayList;
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 © 2014 by John Wiley & Sons. All rights reserved. 59
section_3/Invoice.java
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 items.add(anItem);
30 }
31
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
section_3/Invoice.java
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 Enn"
39 + billingAddress.format()
40 + String.format("nn%-30s%8s%5s%8sn",
41 "Description", "Price", "Qty", "Total");
42
43 for (LineItem item : items)
44 {
45 r = r + item.format() + "n";
46 }
47
48 r = r + String.format("nAMOUNT DUE: $%8.2f", getAmountDue());
49
50 return r;
51 }
52
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
section_3/Invoice.java
53 /**
54 Computes the total amount due.
55 @return the amount due
56 */
57 private double getAmountDue()
58 {
59 double amountDue = 0;
60 for (LineItem item : items)
61 {
62 amountDue = amountDue + item.getTotalPrice();
63 }
64 return amountDue;
65 }
66 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
section_3/LineItem.java
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 © 2014 by John Wiley & Sons. All rights reserved. 63
section_3/LineItem.java
20 /**
21 Computes the total cost of this line item.
22 @return the total price
23 */
24 public double getTotalPrice()
25 {
26 return theProduct.getPrice() * quantity;
27 }
28
29 /**
30 Formats this item.
31 @return a formatted string of this item
32 */
33 public String format()
34 {
35 return String.format("%-30s%8.2f%5d%8.2f",
36 theProduct.getDescription(), theProduct.getPrice(),
37 quantity, getTotalPrice());
38 }
39 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
section_3/Product.java
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 © 2014 by John Wiley & Sons. All rights reserved. 65
section_3/Product.java
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 }
38
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
section_3/Address.java
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
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
section_3/Address.java
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 */
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
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
section_3/Address.java
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 }
40
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Self Check 12.13
Answer: The Invoice class is responsible for computing the
amount due. It collaborates with the LineItem class.
Which class is responsible for computing the amount due?
What are its collaborators for this task?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
Self Check 12.14
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.
Why do the format methods return String objects instead of
directly printing to System.out?

More Related Content

What's hot

Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016BienvenidoVelezUPR
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016BienvenidoVelezUPR
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7dplunkett
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comKeatonJennings91
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsMuhammadTalha436
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 

What's hot (20)

Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
 
Icom4015 lecture4-f17
Icom4015 lecture4-f17Icom4015 lecture4-f17
Icom4015 lecture4-f17
 
Icom4015 lecture13-f16
Icom4015 lecture13-f16Icom4015 lecture13-f16
Icom4015 lecture13-f16
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
 
CBSE 12 ip 2018 sample paper
CBSE 12 ip 2018 sample paperCBSE 12 ip 2018 sample paper
CBSE 12 ip 2018 sample paper
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of Exams
 
M C6java2
M C6java2M C6java2
M C6java2
 
2.oop concept
2.oop concept2.oop concept
2.oop concept
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 

Similar to Icom4015 lecture11-s16

Programming Paradigm Seminar 4
Programming Paradigm Seminar 4Programming Paradigm Seminar 4
Programming Paradigm Seminar 4neoxiuting
 
Sun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock ExamSun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock ExamYasser Ibrahim
 
Online teaching and learning resource guide
Online teaching and learning resource guideOnline teaching and learning resource guide
Online teaching and learning resource guidepabraham8064
 
Software System Engineering - Chapter 10
Software System Engineering - Chapter 10Software System Engineering - Chapter 10
Software System Engineering - Chapter 10Fadhil Ismail
 
An Empirical Study on How Developers Reason about Module Cohesion
An Empirical Study on How Developers Reason about Module CohesionAn Empirical Study on How Developers Reason about Module Cohesion
An Empirical Study on How Developers Reason about Module CohesionBruno C. da Silva
 
2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented ProgramMichael Heron
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented DesignAravinth NSP
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxDrYogeshDeshmukh1
 
Lecture note05 slides
Lecture note05 slidesLecture note05 slides
Lecture note05 slidesSten99String
 
21 cld learning activity rubrics2
21 cld learning activity rubrics221 cld learning activity rubrics2
21 cld learning activity rubrics2SITIAISHAHRAMLI1
 
21cld learning activity rubrics 2012
21cld learning activity rubrics 201221cld learning activity rubrics 2012
21cld learning activity rubrics 2012Khoa (K.A)
 
Sem 2 lesson plan
Sem 2 lesson planSem 2 lesson plan
Sem 2 lesson planAndy Cruz
 
Online PBL: Is this like e-learning with more problems?
Online PBL: Is this like e-learning with more problems?Online PBL: Is this like e-learning with more problems?
Online PBL: Is this like e-learning with more problems?Nadia Naffi, Ph.D.
 
Rethinking Learning: Course Consumption & 21st Century Learning
Rethinking Learning: Course Consumption & 21st Century LearningRethinking Learning: Course Consumption & 21st Century Learning
Rethinking Learning: Course Consumption & 21st Century LearningBrandon Muramatsu
 
M03_1_Structur alDiagrams.ppt
M03_1_Structur                         alDiagrams.pptM03_1_Structur                         alDiagrams.ppt
M03_1_Structur alDiagrams.pptnesarahmad37
 
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docx
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docxW4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docx
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docxmelbruce90096
 
21 cld student work rubrics
21 cld student work rubrics21 cld student work rubrics
21 cld student work rubricssamesu
 

Similar to Icom4015 lecture11-s16 (20)

Grasp
GraspGrasp
Grasp
 
Programming Paradigm Seminar 4
Programming Paradigm Seminar 4Programming Paradigm Seminar 4
Programming Paradigm Seminar 4
 
Sun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock ExamSun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock Exam
 
Online teaching and learning resource guide
Online teaching and learning resource guideOnline teaching and learning resource guide
Online teaching and learning resource guide
 
CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4
 
Software System Engineering - Chapter 10
Software System Engineering - Chapter 10Software System Engineering - Chapter 10
Software System Engineering - Chapter 10
 
An Empirical Study on How Developers Reason about Module Cohesion
An Empirical Study on How Developers Reason about Module CohesionAn Empirical Study on How Developers Reason about Module Cohesion
An Empirical Study on How Developers Reason about Module Cohesion
 
2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
 
Lecture note05 slides
Lecture note05 slidesLecture note05 slides
Lecture note05 slides
 
21 cld learning activity rubrics2
21 cld learning activity rubrics221 cld learning activity rubrics2
21 cld learning activity rubrics2
 
21cld learning activity rubrics 2012
21cld learning activity rubrics 201221cld learning activity rubrics 2012
21cld learning activity rubrics 2012
 
Sem 2 lesson plan
Sem 2 lesson planSem 2 lesson plan
Sem 2 lesson plan
 
Online PBL: Is this like e-learning with more problems?
Online PBL: Is this like e-learning with more problems?Online PBL: Is this like e-learning with more problems?
Online PBL: Is this like e-learning with more problems?
 
Rethinking Learning: Course Consumption & 21st Century Learning
Rethinking Learning: Course Consumption & 21st Century LearningRethinking Learning: Course Consumption & 21st Century Learning
Rethinking Learning: Course Consumption & 21st Century Learning
 
M03_1_Structur alDiagrams.ppt
M03_1_Structur                         alDiagrams.pptM03_1_Structur                         alDiagrams.ppt
M03_1_Structur alDiagrams.ppt
 
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docx
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docxW4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docx
W4 Assignment MIDTERM ExamQuestion 1 1. Students engage i.docx
 
21 cld student work rubrics
21 cld student work rubrics21 cld student work rubrics
21 cld student work rubrics
 

Recently uploaded

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
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
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
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
 

Recently uploaded (20)

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
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🔝
 
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
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
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
 

Icom4015 lecture11-s16

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 12 – Object-Oriented Design
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To learn how to discover new classes and methods  To use CRC cards for class discovery  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
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Discovering Classes  When designing a program, you work from a requirements specification • The designer’s task is to discover structures that make it possible to implement the requirements  To discover classes, look for nouns in the problem description.  Find methods by looking for verbs in the task description.
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Example: Invoice Figure 1 An Invoice
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Example: Invoice  Classes that come to mind: • Invoice • LineItem • Customer  Good idea to keep a list of candidate classes.  Brainstorm: put all ideas for classes onto the list.  Cross not useful ones later.  Concepts from the problem domain are good candidates for classes.  Not all classes can be discovered from the program requirements: • Most programs need tactical classes
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 The CRC Card Method In a class scheduling system, potential classes from the problem domain include Class, LectureHall, Instructor, and Student.
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 The CRC Card Method  After you have a set of classes • Define the behavior (methods) of each class  Look for verbs in the task description • Match the verbs to the appropriate objects  The invoice program needs to compute the amount due • Which class is responsible for this method? o Invoice class
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 The CRC Card Method  To find the class responsibilities, use the CRC card method.  A CRC card describes a class, its responsibilities, and its collaborating classes. • CRC - stands for “classes”, “responsibilities”, “collaborators”  Use an index card for each class.  Pick the class that should be responsible for each method (verb).  Write the responsibility onto the class card.  Indicate what other classes are needed to fulfill responsibility (collaborators).
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 The CRC Card Method Figure 2 A CRC Card
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Self Check 12.1 Answer: Look for nouns in the problem description. What is the rule of thumb for finding classes?
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Self Check 12.2 Answer: Yes (ChessBoard) and no (MovePiece). Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How about MovePiece?
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Self Check 12.3 Answer: PrintStream Suppose the invoice is to be saved to a file. Name a likely collaborator.
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Self Check 12.4 Answer: To produce the shipping address of the customer. Looking at the invoice in Figure 1, what is a likely responsibility of the Customer class?
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Self Check 12.5 Answer: Reword the responsibilities so that they are at a higher level, or come up with more classes to handle the responsibilities. What do you do if a CRC card has ten responsibilities?
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Relationships Between Classes The most common types of relationships:  Dependency  Aggregation  Inheritance
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Dependency  A class depends on another class if it uses objects of that class. The “knows about” relationship.  Example: CashRegister depends on Coin Figure 3 Dependency Relationship Between the CashRegister and Coin Classes
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 Dependency  It is a good practice to minimize the coupling (i.e., dependency) between classes.  When a class changes, coupled classes may also need updating.
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 Aggregation  A class aggregates another if its objects contain objects of the other class. • Has-a relationship  Example: a Quiz class aggregates a Question class.  The UML for aggregation:  Aggregation is a stronger form of dependency.  Use aggregation to remember another object between method calls.
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Aggregation  Use an instance variable public class Quiz { private ArrayList<Question> questions; . . . }  A class may use the Scanner class without ever declaring an instance variable of class Scanner. This is dependency NOT aggregation
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Aggregation A car has a motor and tires. In object-oriented design, this “has-a” relationship is called aggregation.
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Inheritance  Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). • The “is-a” relationship. • Example: Every truck is a vehicle.  Inheritance is sometimes inappropriately used when the has-a relationship would be more appropriate. • Should the class Tire be a subclass of a class Circle? No • A tire has a circle as its boundary • Use aggregation public class Tire { private String rating; private Circle boundary; . . . }
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Inheritance  Every car is a vehicle. (Inheritance)  Every car has a tire (or four). (Aggregation) class Car extends Vehicle { private Tire[] tires; . . . }
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Inheritance  Aggregation denotes that objects of one class contain references to objects of another class. Figure 6 UML Notation for Inheritance and Aggregation
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 UML Relationship Symbols
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 Self Check 12.6 Answer: The CashRegisterTester class depends on the CashRegister, Coin, and System classes. Consider the CashRegisterTester class of Section 8.2. On which classes does it depend?
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Self Check 12.7 Answer: The ChoiceQuestion class inherits from the Question class. Consider the Question and ChoiceQuestion objects of Chapter 9. How are they related?
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Self Check 12.8 Answer: The Quiz class depends on the Question class but probably not ChoiceQuestion, if we assume that the methods of the Quiz class manipulate generic Question objects, as they did in Chapter 9. Consider the Quiz class described in Section 12.2.2. Suppose a quiz contains a mixture of Question and ChoiceQuestion objects. Which classes does the Quiz class depend on?
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Self Check 12.9 Answer: If a class doesn’t depend on another, it is not affected by interface changes in the other class. Why should coupling be minimized between classes?
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Self Check 12.10 Answer: In an e-mail system, messages are stored in a mailbox. Draw a UML diagram that shows the appropriate aggregation relationship.
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Self Check 12.11 Answer: Typically, a library system wants to track which books a patron has checked out, so it makes more sense to have Patron aggregate Book. However, there is not always one true answer in design. If you feel strongly that it is important to identify the patron who checked out a particular book (perhaps to notify the patron to return it because it was requested by someone else), then you can argue that the aggregation should go the other way around. You are implementing a system to manage a library, keeping track of which books are checked out by whom. Should the Book class aggregate Patron or the other way around?
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 Self Check 12.12 Answer: There would be no relationship. In a library management system, what would be the relationship between classes Patron and Author?
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Attributes and Methods in UML Diagrams
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Multiplicities  any number (zero or more): *  one or more: 1..*  zero or one: 0..1  exactly one: 1
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Aggregation and Association, and Composition  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.
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Aggregation and Association, and Composition  Composition: one of the classes can not exist without the other.
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Application: Printing an Invoice Five-part program 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
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Application: Printing an Invoice - Requirements  Start the development process by gathering and documenting program 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.
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Application: Printing an Invoice Sample Invoice I N V O I C E Sam's Small Appliances 100 Main Street Anytown, CA 98765 Description Price Qty Total Toaster 29.95 3 89.85 Hair dryer 24.95 1 24.95 Car vacuum 19.99 2 39.98 AMOUNT DUE: $154.78
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Application: Printing an Invoice An invoice lists the charges for each item and the amount due.
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Application: Printing an Invoice – CRC Cards  Use CRC cards to find classes, responsibilities, and collaborators.  Discover classes  Nouns are possible classes: Invoice Address LineItem Product Description Price Quantity Total Amount Due
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 Application: Printing an Invoice – CRC Cards  Analyze classes: Invoice Address LineItem // Records the product and the quantity Product Description // Field of the Product class Price // Field of the Product class Quantity // Not an attribute of a Product Total // Computed - not stored anywhere Amount Due // Computed - not stored anywhere  Classes after a process of elimination: Invoice Address LineItem Product
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 CRC Cards for Printing Invoice Invoice and Address must be able to format themselves:
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 CRC Cards for Printing Invoice Add collaborators to Invoice card:
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 CRC Cards for Printing Invoice Product and LineItem CRC cards:
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 CRC Cards for Printing Invoice Invoice must be populated with products and quantities:
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Application: Printing an Invoice – UML Diagrams
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Printing an Invoice — Method Documentation  Use javadoc comments (with the method bodies left blank) to record the behavior of the classes.  Write a Java source file for each class: • Write the method comments for those methods that you have discovered, • 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
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 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) { } /** Formats the invoice. @return the formatted invoice */ public String format() { } }
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 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() { } /** Formats this item. @return a formatted string of this line item */ public String format() { } }
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 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() { } /** Gets the product price. @return the unit price */ public double getPrice() { } }
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 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() { } }
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 The Class Documentation in the HTML Format Figure 8 Class Documentation in HTML Format
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Printing an Invoice — Implementation  After completing the design, implement your classes.  The UML diagram will give instance variables: • Look for aggregated classes • They yield instance variables
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 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; }
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Implementation  A line item needs to store a Product object and quantity: public class LineItem { . . . private int quantity; private Product theProduct; }
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 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; }  Also supply constructors
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 section_3/InvoicePrinter.java 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&apos;s Small Appliances", 11 "100 Main Street", "Anytown", "CA", "98765"); 12 13 Invoice samsInvoice = new Invoice(samsAddress); 14 samsInvoice.add(new Product("Toaster", 29.95), 3); 15 samsInvoice.add(new Product("Hair dryer", 24.95), 1); 16 samsInvoice.add(new Product("Car vacuum", 19.99), 2); 17 18 System.out.println(samsInvoice.format()); 19 } 20 } 21 22 23
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 section_3/Invoice.java 1 import java.util.ArrayList; 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
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 section_3/Invoice.java 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 items.add(anItem); 30 } 31 Continued
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 section_3/Invoice.java 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 Enn" 39 + billingAddress.format() 40 + String.format("nn%-30s%8s%5s%8sn", 41 "Description", "Price", "Qty", "Total"); 42 43 for (LineItem item : items) 44 { 45 r = r + item.format() + "n"; 46 } 47 48 r = r + String.format("nAMOUNT DUE: $%8.2f", getAmountDue()); 49 50 return r; 51 } 52 Continued
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 section_3/Invoice.java 53 /** 54 Computes the total amount due. 55 @return the amount due 56 */ 57 private double getAmountDue() 58 { 59 double amountDue = 0; 60 for (LineItem item : items) 61 { 62 amountDue = amountDue + item.getTotalPrice(); 63 } 64 return amountDue; 65 } 66 }
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 section_3/LineItem.java 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
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 section_3/LineItem.java 20 /** 21 Computes the total cost of this line item. 22 @return the total price 23 */ 24 public double getTotalPrice() 25 { 26 return theProduct.getPrice() * quantity; 27 } 28 29 /** 30 Formats this item. 31 @return a formatted string of this item 32 */ 33 public String format() 34 { 35 return String.format("%-30s%8.2f%5d%8.2f", 36 theProduct.getDescription(), theProduct.getPrice(), 37 quantity, getTotalPrice()); 38 } 39 }
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 section_3/Product.java 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
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 section_3/Product.java 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 } 38
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 section_3/Address.java 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 Continued
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 section_3/Address.java 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 */ 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 Continued
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 section_3/Address.java 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 } 40
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Self Check 12.13 Answer: The Invoice class is responsible for computing the amount due. It collaborates with the LineItem class. Which class is responsible for computing the amount due? What are its collaborators for this task?
  • 70. Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 Self Check 12.14 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. Why do the format methods return String objects instead of directly printing to System.out?