99
Sep. 28, 2006 1 CHAPTER 12 OBJECT-ORIENTED ANALYSIS

CHAPTER 12

  • Upload
    garry

  • View
    41

  • Download
    0

Embed Size (px)

DESCRIPTION

CHAPTER 12. OBJECT-ORIENTED ANALYSIS. Object-Oriented Analysis. OOA is a semiformal analysis technique for the object-oriented paradigm There are over 60 equivalent techniques Today, the Unified Process is the only viable alternative During this workflow The classes are extracted. - PowerPoint PPT Presentation

Citation preview

Page 1: CHAPTER 12

Sep. 28, 2006 1

CHAPTER 12

OBJECT-ORIENTED ANALYSIS

Page 2: CHAPTER 12

Sep. 28, 2006 2

Object-Oriented Analysis

OOA is a semiformal analysis technique for the object-oriented paradigm– There are over 60 equivalent techniques– Today, the Unified Process is the only viable

alternative

During this workflow– The classes are extracted

Page 3: CHAPTER 12

Sep. 28, 2006 3

Object-Oriented Analysis/Design Object: is a component of the real world that is mapped

into the software domain. A class is a set of objects that each has the same characteristics.

Encapsulation: is an act of grouping into a single object both data and the operations that affect data.

Information-hiding: The private side of an object is how it does these things, and it can do them in any way required. How it performs the operations or computes the information is not a concern of other parts of the system.

Page 4: CHAPTER 12

Sep. 28, 2006 4

Classes Subclass is a class that inherits behavior

from another class. A subclass usually adds its own behavior to

define its own unique kind of object. Superclass is a class from which a specific

behavior is inherited. Abstract Class: class that is not intended to

produce instances of itself.

Page 5: CHAPTER 12

Sep. 28, 2006 5

Messages

A message consists of the name of an operation and any required argument.

Polymorphism is the ability of two or more classes of object to respond to the same message, each in its own way.

Page 6: CHAPTER 12

Sep. 28, 2006 6

The Analysis Workflow

There are three types of classes:

Entity classes

Boundary classes

Control classes

Page 7: CHAPTER 12

Sep. 28, 2006 7

The Analysis Workflow (contd)

Entity class– Models long-lived information

Examples:– Account Class– Investment Class

Page 8: CHAPTER 12

Sep. 28, 2006 8

The Analysis Workflow (contd)

Boundary class– Models the interaction between the product and the

environment– A boundary class is generally associated with input or

output

Examples:– Investments Report Class– Mortgages Report Class

Page 9: CHAPTER 12

Sep. 28, 2006 9

The Analysis Workflow (contd)

Control class– Models complex computations and algorithms

Example:– Estimate Funds for Week Class

Page 10: CHAPTER 12

Sep. 28, 2006 10

UML Notation for These Three Class Types

Stereotypes (extensions of UML)

Figure 12.1

Page 11: CHAPTER 12

Sep. 28, 2006 11

12.5.2 CRC Cards Used since 1989 for OOA

For each class, fill in a card showing– Name of Class– Functionality (Responsibility)– List of classes it invokes (Collaboration)

Now CRC cards are automated (CASE tool component)

Page 12: CHAPTER 12

Sep. 28, 2006 12

The Process of OOA/D-The CRC approach

Find the classes in your system. Determine what operations each class is

responsible for performing, and what knowledge it should maintain.

Determine the ways in which objects collaborate with other objects in order to discharge their responsibilities.

Page 13: CHAPTER 12

Sep. 28, 2006 13

The Process of OOA/D

a list of classes within your application, a description of the knowledge and

operations for which each class is responsible, and

a description of collaborations between classes.

Page 14: CHAPTER 12

Sep. 28, 2006 14

Exploratory Phase

Extract noun phrases from the specification and build a list.

Walk through various scenarios to explore possibilities.

Record the results on design cards.

Page 15: CHAPTER 12

Sep. 28, 2006 15

Classes - Exploratory Phase Extract noun phrases from the specification and build a list. Look for nouns that may be hidden, and add them to the list. Identify candidate classes from the noun phrases by applying the following

guidelines:– Model physical objects.– Model conceptual entities.– Use a single term for each concept.– Be wary of the use of adjectives.– Model categories of objects.– Model external interfaces.– Model the values of an object's attributes.

Identify candidates for abstract superclasses by grouping classes that share common attributes.

Use categories to look for classes that may be missing. Write a short statement of the purpose of the class.

Page 16: CHAPTER 12

Sep. 28, 2006 16

Responsibilities - Exploratory Phase Find responsibilities using the following guidelines:

– Recall the purpose of each class, as implied by its name and – specified in the statement of purpose.– Extract responsibilities from the specification by looking for actions and

information.– Identify responsibilities implied by the relationships between classes.

Assign responsibilities to classes using the following guidelines:– Evenly distribute system intelligence.– State responsibilities as generally as possible.– Keep behavior with related information.– Keep information about one thing in one place.– Share responsibilities among related classes.

Find additional responsibilities by looking for relationships between classes.– Use ``is-kind-of'' relationships to find inheritance relationships.– Use ``is-analogous-to'' relationships to find missing superclasses.– Use ``is-part-of'' relationships to find other missing classes.

Page 17: CHAPTER 12

Sep. 28, 2006 17

Collaborations - Exploratory Phase Find and list collaborations by examining the

responsibilities associated with classes. Ask:– With whom does this class need to collaborate to fulfill its

responsibilities?– Who needs to make use of the responsibilities defined for this

class? Identify additional collaborations by looking for these

relationships between classes:– the ``is-part-of'' relationship,– the ``has-knowledge-of'' relationship, and– the ``depend-upon'' relationship.

Discard classes if no classes collaborate with them, and they collaborate with no other classes.

Page 18: CHAPTER 12

Sep. 28, 2006 18

A product is to be installed to control n elevators in a building with m floors. The problem concerns the logic required to move elevators between floors according to the following constraints:1. Each elevator has a set of m buttons, one for each floor. These illuminate when pressed and cause the elevator to visit the corresponding floor. The illumination is canceled when the corresponding floor is visited by the elevator2. Each floor, except the first and the top floor, has two buttons, one to request an up-elevator, one to request a down-elevator. These buttons illuminate when pressed. The illumination is canceled when an elevator visits the floor, then moves in the desired direction 3. If an elevator has no requests, it remains at its current floor with its doors closed

Page 19: CHAPTER 12

Sep. 28, 2006 19

12.5.1 Noun Extraction A two-stage process Stage 1. Concise problem definition

– Describe the software product in single paragraph – Buttons in elevators and on the floors control the

movement of n elevators in a building with m floors. Buttons illuminate when pressed to request the elevator to stop at a specific floor; the illumination is canceled when the request has been satisfied. When an elevator has no requests, it remains at its current floor with its doors closed

Page 20: CHAPTER 12

Sep. 28, 2006 20

Noun Extraction (contd) Stage 2. Identify the nouns

– Identify the nouns in the informal strategy– Buttons in elevators and on the floors control the movement of n

elevators in a building with m floors. Buttons illuminate when pressed to request the elevator to stop at a specific floor; the illumination is canceled when the request has been satisfied. When an elevator has no requests, it remains at its current floor with its doors closed

Use the nouns as candidate classes

Page 21: CHAPTER 12

Sep. 28, 2006 21

Noun Extraction (contd) Nouns

– button, elevator, floor, movement, building, illumination, request, door – floor, building, door are outside the problem boundary — exclude– movement, illumination, request are abstract nouns — exclude (they may become

attributes)

Candidate classes: – Elevator Class and Button Class

Subclasses: – Elevator Button Class and Floor Button Class

Page 22: CHAPTER 12

Sep. 28, 2006 22

First Iteration of Class Diagram

Problem– Buttons do not communicate directly with elevators– We need an additional class: Elevator Controller Class

Figure 12.5

Page 23: CHAPTER 12

Sep. 28, 2006 23

Second Iteration of Class Diagram

Figure 12.6

Page 24: CHAPTER 12

Sep. 28, 2006 24

12.6 Dynamic Modeling: The Elevator Problem Case Study

Figure 12.7

Page 25: CHAPTER 12

Sep. 28, 2006 25

Dynamic Modeling: Elevator Problem (contd)

This UML statechart is equivalent to the state transition diagram of Figures 11.15 through 11.17

This is shown by considering specific scenarios

In fact, a statechart is constructed by modeling the events of the scenarios

Page 26: CHAPTER 12

Sep. 28, 2006 26Figure 12.8

Page 27: CHAPTER 12

Sep. 28, 2006 27

CRC Cards Consider responsibility

– 1. Turn on elevator button

This is totally inappropriate for the object-oriented paradigm– Responsibility-driven design has been ignored– Information hiding has been ignored

Responsibility 1. Turn on elevator button

should be1. Send message to Elevator Button Class to turn itself on

Page 28: CHAPTER 12

Sep. 28, 2006 28

CRC Cards (contd) Also, a class has been overlooked

The elevator doors have a state that changes during execution (class characteristic)– Add class Elevator Doors Class– Safety considerations

Modify the CRC card

Page 29: CHAPTER 12

Sep. 28, 2006 29

Second Iteration of the CRC Card

Figure 12.9

Page 30: CHAPTER 12

Sep. 28, 2006 30

CRC Cards (contd) Having modified the class diagram,

reconsider the– Use-case diagram (no change)– Class diagram (see the next slide)– Statecharts – Scenarios (see the slide after the next slide)

Page 31: CHAPTER 12

Sep. 28, 2006 31

Third Iteration of Class Diagram

Figure 12.10

Page 32: CHAPTER 12

Sep. 28, 2006 32

Responsibilities– 8. Start timer– 10. Check requests, and– 11. Update requests

are assigned to the elevator controller

Because they are carried out by the elevator controller

Page 33: CHAPTER 12

Sep. 28, 2006 33

The remaining eight responsibilities have the form– “Send a message to another class to tell it do

something”These should be assigned to that other class

– Responsibility-driven design– Safety considerations

Methods open doors, close doors are assigned to class Elevator Doors

Methods turn off button, turn on button are assigned to classes Floor Button and Elevator Problem

Page 34: CHAPTER 12

Sep. 28, 2006 34Figure 13.11

Detailed Class Diagram: Elevator Problem

Page 35: CHAPTER 12

Sep. 28, 2006 35

Detailed Design: Detailed design

of elevatorEventLoop is constructed from the statechart

Figure 13.12

Page 36: CHAPTER 12

Sep. 28, 2006 36

Software Design

Software Design-``a system decomposition into modules-description of what each module is intended to do and of the relationship among the modules.'‘

Design for Change Program Families

Page 37: CHAPTER 12

Sep. 28, 2006 37

Design Process Management Aspects:

– Preliminary design (high level design)– Detail design (low level design)

Technical Aspects:– Data design– Architectural design– Procedure design– Interface design

Page 38: CHAPTER 12

Sep. 28, 2006 38

Effective modular design

Functional Independence– coupling: is a measure of the relative

interdependence among modules.– cohesion: is a measure of the relative functional

strength of a module

Page 39: CHAPTER 12

Sep. 28, 2006 39

Coupling

Coupling is a measure of interconnection among modules in a software structure.

Coupling depends on the interface complexity between modules.

Page 40: CHAPTER 12

Sep. 28, 2006 40

Cohesion Coincidental cohesion: A module that performs a set of tasks

that relate to each other loosely. Logical cohesion: A module that performs tasks that are

related logically. Temporal cohesion: A module that performs tasks that are

related by the fact that all must be executed with the same span of time.

Procedure cohesion: A module that processes elements that are related and must be executed in a specific order.

Communicational cohesion: A module that processes elements that all concentrate on one area of a data structure.

Sequential cohesion: The output data from an element is the input for the next element.

Functional cohesion: All of the elements are related to the performance of a single function.

Page 41: CHAPTER 12

Sep. 28, 2006 41

Coupling No direct coupling: two modules are subordinate to different

modules. Data coupling: data passed via a module interface. Stamp Coupling: data structure passed via a module interface. Control coupling: control is passed via a ``flag'' on which

decisions are made in a subordinate or supordinate module. External coupling: Modules are tied to an environment external

to software. Common coupling: a number of modules reference a global data

area. Content coupling: one module makes use of data or control

information `maintained within the boundary of another module.

Page 42: CHAPTER 12

Sep. 28, 2006 42

Design Heuristics Evaluate the ``First-Cut'' Program Structure to Reduce Coupling

and Improve Cohesion. Attempt to Minimize Structures with High Fan-Out; Strive for

Fan-In as Depth Increases. Keep Scope of Effect of a Module within the scope of Control of

that Module. Evaluate Module Interfaces to Reduce Complexity and

Redundancy and Improve Consistency. Define Modules Whose Function is Predictable, But Avoid

Modules That are overly restrictive. Strive for Single-Entry-Single-Exit Modules, Avoiding

``Pathological Connections.'' Package Software Based on Design Constraints and Portability

Requirements.

Page 43: CHAPTER 12

Sep. 28, 2006 43

Design Metrics Metrics: “a quantitative measure of the degree to which a system,

component, or process possesses a given attribute.” [IEEE93] LOC Cyclomatic complexity: McCabe, 1976

– V(G) = P + 1, V(G) = E – N + 2 Function point: Albrecht, 1979

– FP entities: # of user inputs, # of user outputs, # of user inquiries, # of files, # of external interfaces

– FP = count total * [0.65 + 0.01 * sum(fi )]Where fi ( 1 ~ 14) are value adjustment value factors based on the responses to 14 questions. Count total is the

sum of weighted FP entities. Henry and Kafura, 1981

– Length * (fan-in * fan-out)2

Page 44: CHAPTER 12

Sep. 28, 2006 44

Chidamber & Kemerer (CK) Metrics

Weighted Methods per Class (WMC) Depth of Inheritance Tree (DIT) Number of Children (NOC) Coupling Between Object Classes(CBO) Response For a Class (RFC) Lack of Cohesion in Methods (LCOM)

Page 45: CHAPTER 12

Sep. 28, 2006 45

Weighted Methods Per Class (WMC)

Consider a Class C1 , with methods M1, …, Mn that are defined in the class. Let c1, …, cn be the complexity of the methods. Then:

WMC =

If all method complexities are considered to be unity, then

WMC = n

n

iic

1

Page 46: CHAPTER 12

Sep. 28, 2006 46

WMC ExampleClass foo {

int local_var;int *pInt;

public:foo(){local var = 1; pInt = new int;}int f1(){return local_var;}int f2(){return ++local_var;}int f3(){return 1/f1();}

}

Assume all methods with the same complexity:

WMC(foo) = 4

Page 47: CHAPTER 12

Sep. 28, 2006 47

Depth of Inheritance Tree (DIT)

Depth of inheritance of the class is the DIT metric for the class.

DIT = depth of the class in the inheritance tree

If multiple inheritance is allowed, DIT = the maximum length

from the node to the root of the tree

Page 48: CHAPTER 12

Sep. 28, 2006 48

Number of Children (NOC)

NOC = number of immediate subclasses subordinated to a class in the class hierarchy

Page 49: CHAPTER 12

Sep. 28, 2006 49

Coupling Between Objects (CBO)

A count of the number of other classes to which it is coupled.– An object is coupled to another object if one of

them acts on the other.– Two classes are coupled when methods

declared in one class use methods or instance variables defined by the other class.

Page 50: CHAPTER 12

Sep. 28, 2006 50

CBO Example

Class A { :M1(){

:B.M1();

C.M2();: }

}CBO (A) = 2

Class B { :M1(){

: } }

Class C { :M2(){

: }}

Page 51: CHAPTER 12

Sep. 28, 2006 51

Response for a Class (RFC)

RFC = | RS | where RS is the response set for the class

RS = {M} all i {Ri} where{Ri} = set of methods called by method I and

{M} = set of all methods in the class

Page 52: CHAPTER 12

Sep. 28, 2006 52

RFC Example

Class C1{M1(){…};M2 (){…};M3(){… C2.M1()};}

Class C2{M1(){…};}

RFC = 3 + 1 = 4

Page 53: CHAPTER 12

Sep. 28, 2006 53

Lack of Cohesion in Methods (LCOM)

• Consider a Class C1 , with n methods M1, …, Mn. Let {Ij}= set of instance variables used by method Mi. There are n such sets {I1}, …, {In}. Let P = {(Ii, Ij)| Ii Ij = } and Q = {(Ii, Ij)| Ii Ij }. If all n sets {I1}, …, {In} are then let P = .

LCOM = | P | - | Q | , if | P | > | Q | = 0 , otherwise

Page 54: CHAPTER 12

Sep. 28, 2006 54

LCOM Example

• Consider a Class C with 3 methods M1, M1 and M3. Let {I1}= {a, b, c, d, e}, {I2}= {a, b, c} and {I3}= {x, y, z}.

• {I1} {I2} is nonempty, but {I1} {I3} and {I2} {I3} are null sets.

LCOM = | P | - | Q | = 2 – 1 = 1

Page 55: CHAPTER 12

Sep. 28, 2006 55

Object Modeling

The object model is composed of– Classes– Associations

Page 56: CHAPTER 12

Sep. 28, 2006 56

Mapping Persistent Classes to Tables

In a relational database– Every row is regarded as an object– A column in a table is equivalent to a persistent

attribute of a class

Page 57: CHAPTER 12

Sep. 28, 2006 57

Mapping Associations Between Persistent Objects

Associations between two persistent objects are realized as foreign keys to the associated objects– A foreign key is a column in one table which

contains the primary key value of associated object

Page 58: CHAPTER 12

Sep. 28, 2006 58

Mapping Aggregation to the Data Model

Aggregation is also modeled using foreign key relationships– Using composition implements a cascading

delete constraint

Page 59: CHAPTER 12

Sep. 28, 2006 59

Mapping inheritance in the Data Model

A data model does not support modeling inheritance in a direct way

Two options– Use separate tables (normalized data)– Duplicate all inherited associations and

attributes(de-normalized data)

Page 60: CHAPTER 12

Sep. 28, 2006 60

Aggregation

Many objects that have properties and interfaces and methods are really made up of combinations of smaller objects that have their own properties and interfaces and methods.

For example, a stove is made up (typically) of four burners, an oven and some controls.

Page 61: CHAPTER 12

Sep. 28, 2006 61

Aggregation (continued)

Each burner has its own properties (it can have a temperature) and its own interface (sending electricity through it causes it to heat) and methods (it can heat a pot of water).

An oven has similar properties, and a similar interface, and it has its own methods (it can cook a turkey).

Page 62: CHAPTER 12

Sep. 28, 2006 62

Aggregation

A stove combines these burner and oven objects, along with some controls and a power cord, to make a larger object with more capabilities than any of its parts have individually (it can heat a pot of water and cook a turkey).

Page 63: CHAPTER 12

Sep. 28, 2006 63

Aggregation

The stove also hides the interfaces of the component objects that it is made of (I.e. the “electricity” interface of the burners and stove) and provides a more “user-friendly” interface (I.e. knobs to turn on burners and oven)

Page 64: CHAPTER 12

Sep. 28, 2006 64

Aggregation

When you turn a knob to “on”, the stove uses the burner’s “electricity” interface to send it a signal to heat up. We say that the burner “knows how to heat up” or has the “capability” to heat up, and that the stove object is “sending a message” to the burner (via initiating an electric current) to use the burner’s “heat up” method.

Page 65: CHAPTER 12

Sep. 28, 2006 65

Aggregation

The process of a taking a bunch of simpler objects (I.e. burners) and using these objects to create a more complex object (I.e. a stove) is called “aggregation”, and we say that the more complex object (the stove) aggregates the simpler objects (the burners).

Page 66: CHAPTER 12

Sep. 28, 2006 66

Aggregation

Aggregation is the idea of a bunch of “smart objects” that all “know how to do things” cooperating with each other to form some larger functionality.

Page 67: CHAPTER 12

Sep. 28, 2006 67

Aggregation Another good example of aggregation is a computer.

No one piece of a computer can work separately. A disk drive “knows” how to store data, a monitor “knows” how to display graphics, a cd-rom drive “knows” how to read a cd, memory chips “know” how to store numbers. A computer “aggregates” these and other objects into a single object that can do many things by using each of the aggregated objects to perform different tasks needed to, for example, display a document on the screen, edit it, and save it for later use.

Page 68: CHAPTER 12

Sep. 28, 2006 68

Modeling aggregation in UML

HeatAPot()HeatATurkey()

_burner1_burner2_oven_burner1on_burner2on

Stove

HeatUp()_temperature

Burner

HeatUp()_temperature

Oven

1*

1

*

Page 69: CHAPTER 12

Sep. 28, 2006 69

Notes about aggregation

Aggregation is also sometimes called composition, as in “a stove is composed of an oven and some burners”.

Aggregation is also referred to as the “has-a” relationship, as in “a stove has an oven and a stove has burners”

Page 70: CHAPTER 12

Sep. 28, 2006 70

Modeling Aggregation in Java

First, some mechanics. Recall that when we create an instance of a class in Java, space is allocated for that instance in memory. The space will be allocated at a certain address. We can use this address as a handle to the instance of the class by using a special type of variable called a reference variable.

Page 71: CHAPTER 12

Sep. 28, 2006 71

Modeling Aggregation in Java

A reference variable is a variable that can hold the address of an instance of a class. Let’s say that we want to hold the address of an instance of the Burner class. We define a variable:

Burner _myBurner;Then we set this variable equal to an instance of the

burner class:_myBurner = new Burner( );

Page 72: CHAPTER 12

Sep. 28, 2006 72

Modeling Aggregation in Java

Notice that the type of the variable that we declare to hold the reference is the name of the class whose instances the variable will hold a reference to. This makes sense; in some way, the ‘type’ of information our variable is holding is a ‘Burner’, or a reference to an instance of the Burner class.

Burner _myBurner;Burner _myBurner;

Page 73: CHAPTER 12

Sep. 28, 2006 73

Modeling Aggregation in Java

Here’s what the reference variable looks like in use:

Memory

_myburner

Instance of burner class

_temperature 0

Page 74: CHAPTER 12

Sep. 28, 2006 74

Modeling Aggregation In Java

We can use reference variables to model aggregation in java by having an instance of the aggregating class (I.e. the stove) hold a reference to an instance of the aggregated class (I.e. the burner), modeling the connection in the real world system.

Page 75: CHAPTER 12

Sep. 28, 2006 75

Modeling Aggregation In Java Here’s what it looks like in code:

class Stove

{

Burner _burner1;

Burner _burner2;

Oven _theOven;

Stove( )

{

_burner1 = new Burner( );

_burner2 = new Burner( );

_theOven = new Oven( );

}

}

class Burner

{

int _temperature;

}

class Oven

{

int _temperature;

}

Page 76: CHAPTER 12

Sep. 28, 2006 76

Here’s what it looks like in memory:

Instance of Stove class

_burner1_burner2_theOven

_temperature

Instance of Burner class

_temperature

Instance of Burner class_temperature

Instance of Oven class

1 1 new Stove( );

An instance of the Stove class is created

2

2_burner1 = new Burner( )

The constructor of the Stove class is called to set up the new instance, and creates an instance of the Burner class

3

3The Stove class constructor stores a reference to the new instance of the Burner class in the instance variable _burner1 (and then repeats all three steps for _burner2 and _stove)

_burner1 = new Burner( );

0

0

0

Page 77: CHAPTER 12

Sep. 28, 2006 77

Page 78: CHAPTER 12

Sep. 28, 2006 78

Page 79: CHAPTER 12

Sep. 28, 2006 79

The VCR knows about the television and uses the television.But the television is not inside the VCR, nor should we say the television is a part of the VCR.We say the VCR is associated with the television.

AssociationAssociation

Page 80: CHAPTER 12

Sep. 28, 2006 80

AssociationAssociationHere’s what it looks like in UML:

-_television

VCR Television

1 1

Note the two red 1’s on either side of the link. These are called “multiplicity indicators”. They simply tell us how many instances of each class are involved in the relationship. In this case, 1 VCR associates with 1 television (which makes sense). (We can also use these multiplicity numbers with aggregation).

Page 81: CHAPTER 12

Sep. 28, 2006 81

How do we model association in Java? First, now that we know about methods,

let’s realize that a constructor is really just a method:

VCR( )

{

_display = new Display( );

}

AssociationAssociation

Page 82: CHAPTER 12

Sep. 28, 2006 82

Constructors, like any other method, can have parameters.

And a parameter can be not only an int or a boolean, it can also be a reference to an instance of a class.

VCR( )

{

_display = new Display( );

}

AssociationAssociation

Page 83: CHAPTER 12

Sep. 28, 2006 83

So what we will do is:1. We will create an instance of a television

class2. We will pass a reference to that instance to

the constructor method of the VCR class3. We will store a reference to the instance of

the television class in an instance variable of the VCR class.

AssociationAssociation

Page 84: CHAPTER 12

Sep. 28, 2006 84

Now, let’s add a parameter to the constructor method of our VCR class so that we can pass a reference to an instance of the Television class to the VCR constructor method. Note that we also create an instance variable to hold the reference.

public class Television

{

int channel;

TV( )

{

channel = 2;

}

}

public class VCR

{

Television _myTV;

VCR( Television tv)

{

_myTV = tv;

}

}

AssociationAssociation

Page 85: CHAPTER 12

Sep. 28, 2006 85

Now, let’s see how we create a TV and VCR and “hook them up to each other”, or, more precisely, associate them:

Television robsTV = new Television( );

VCR robsVCR = new VCR(robsTV);

AssociationAssociation

Page 86: CHAPTER 12

Sep. 28, 2006 86

Here’s what it looks like in memory:

Television instance

_channel

Memory

1. Television robsTV = new Television( );

A new instance of the Television class is created

_myTV

Page 87: CHAPTER 12

Sep. 28, 2006 87

Here’s what it looks like in memory:

Television instance

_channel 2

Memory

2. _channel = 2;

The constructor method of the Television class is executed and sets the _channel variable to its initial value, 2.

Temporary memory allocated for execution of constructor

_myTV

Page 88: CHAPTER 12

Sep. 28, 2006 88

Here’s what it looks like in memory:

Television instance

_channel 2

Memory3. VCR robsVCR = new VCR(robsTV)

A new instance of the VCR class is created, and a reference to the “robsTV” instance of the Television class is passed to the VCR constructor, which is then stored as the value of the constructor method’s parameter “tv”

VCR instance

_myTV

Temporary memory for execution of constructor

tv

_myTV

Page 89: CHAPTER 12

Sep. 28, 2006 89

Here’s what it looks like in memory:

VCR instance

_myTV

Television instance

_channel 2

MemoryVCR( Television tv)

{

_myTV = tv;

}

4. The constructor method of the VCR class stores this reference in the instance variable “_myTV”

Temporary memory for execution of constructor

tv

Page 90: CHAPTER 12

Sep. 28, 2006 90

Here’s what it looks like in memory:

Television instance

_channel 2

Memory

And we have the final picture we wanted, where the VCR “associates with” or “knows about” the television.

VCR instance

_myTV

Page 91: CHAPTER 12

Sep. 28, 2006 91

Note that association is very similar to aggregation.

The main difference is “who creates the parts”

In aggregation, we have an object that is “inside of” another object, I.e. a display that is inside of a vcr.

The “outer object” creates the “inner object” and points to it

I.e. the VCR creates its display and points to it

AssociationAssociation

Page 92: CHAPTER 12

Sep. 28, 2006 92

In association, we have two objects that know about each other but are not “inside of” one another.

So someone creates one object, I.e. some other class creates a television

Then someone creates the other object, I.e. the VCR, and “tells it about” the associated object, I.e. the TV, by passing a reference to the associated object (I.e. the TV) to the associating object’s (I.e. the VCR) constructor

AssociationAssociation

Page 93: CHAPTER 12

Sep. 28, 2006 93

The important thing to note about association versus aggregation is this:

It makes sense to have a VCR create its display, because we would not have or need a VCR display without a VCR.

It does not make sense to have a VCR create our television, because we very well might have a television before or without having a VCR.

AssociationAssociation

Page 94: CHAPTER 12

Sep. 28, 2006 94

If we had our VCR create our television, we would never be able to have a television without having a VCR

Which would not be a good model of the real world.

AssociationAssociation

Page 95: CHAPTER 12

Sep. 28, 2006 95

Page 96: CHAPTER 12

Sep. 28, 2006 96

Association

Page 97: CHAPTER 12

Sep. 28, 2006 97

Page 98: CHAPTER 12

Sep. 28, 2006 98

Inheritance

Page 99: CHAPTER 12

Sep. 28, 2006 99