Lecture 5-6
Lecture 5-6
Composition, and
Dependence
Relationships Among
Classes
Lect 5—6
14-08-2023
1
Aggregation Relationship
Represents whole-part relationship
Represented by a diamond symbol at the aggregator
end.
*
1
Company *
employs Person memberOf Club
Often indistinguishable from plain association.
However:
Aggregate usually creates the components.
Aggregate usually invokes the same operations on
all its components.
Usually aggregate is owner of the components:
But may share with other objects
2
Aggregation: Two Examples
Document 1
* Paragraph 1 * Line
Company 1
employs
* 1
Person* memberOf Club
3
Aggregation cont…
An aggregate object contains other
objects.
Aggregation limited to tree
hierarchy:
No circular inclusion relation. Line
Paragraph
1
*
4
Composition
A stronger form of aggregation
The whole is sole owner of its part.
A component can belong to only one whole
1 Circle
Circle Point
3..* Point
Polygon
5
Composition Relationship
Life of item is same as that of order
1
Order * Item
6
Composition: Alternate Notation
Car
4 1
Wheel Engine
2 1
Door Chassis
1 1
Axle
Steering
7
Composition
• An object (component) may be a part of
ONLY one composite.
Whole is responsible for the creation and
disposition of its parts.
Windowwhole
*
Frame part
8
Aggregation vs. Composition
Composition:
Composite and its components
have the same life line.
Aggregation:
Lifelines are different.
Consider an order object:
Aggregation: If order items can be
changed or deleted after placing an order.
Composition: Otherwise. 9
Composition versus Aggregation
1
Order * Item Compositio
n
1
* Aggregation
Order Item
10
Implementing Composition…
public class Car{
private Wheel wheels[4];
1 4 Wheel
public Car (){ Car
wheels[0] = new Wheel();
wheels[1] = new Wheel();
wheels[2] = new Wheel();
wheels[3] = new Wheel();
}
} 11
12
Aggregation: Code Example
An aggregation relationship is usually represented as a data field in
Person Name
*
13
Often Inner Classes are Used
If House is used public class Person
{
only in the
private Name
Person class: name;
Declare it as an private House
inner class in house;
Person. ...
class House {
...
} 14
Implementing Aggregation:
Ex 1
import java.util.ArrayList;
public class CarShop{
CarCompany company; Manager
manager;
private ArrayList<SalesPerson> people =
new ArrayList<SalesPerson>();
private ArrayList<Car> cars = new
ArrayList<Car>(); * Car
1
} Car Shop
* Salesman 15
Deciding Whether to Use Composition or
Aggregation…
Use composition if:
Lifetime of part is bound with lifetime of
composite
19
Dependency
Common Dependences are caused by:
Local variables
Parameters
Return values
Example:
Class A {Class B {
B Foo(B x) { …
B y = new B(); …
return y; …
}
} }
20
Dependence – Examples
class MyDependentClass{
void
MyClass myFunction1( MyRefere
att: int ncedClass r ) { .. }
myFunction() MyreferencedClass
myFunction2( .. ) { .. }
dependence
arrow
void myFunction3( .. )
{ MyReferencedClass m
MyReferencedClass
.. }
} 21
Association Vs. Aggregation
Is aggregation an association?
Is composition an aggregation?
22
Summary of Three Class Relations
Car
aggregation: "is part of"
1
aggregati
Symbolized by empty diamond 1
on
Engine
composition: “is made of”
Book
Stronger version of aggregationcompositio
n 1
The parts live and die with the
whole Page
*
Class
Generalization dependen
Relationship cy
Object Object
Aggregation Composition
Object Association Association Association
1..* 1
n m
* *
Faculty SalesOrder
(team- 1..5 1
teaching
is
possible)
* 1..*
Course SalesOrderLineItem
25
Multiplicity Quiz #1
Whole
Class
1 3
diagram
5 2
Part A Part B
Read
•One Whole is associated with 5 •One Whole is associated with 2 PartB
Part A •One PartB is associated with 3 Whole
•One Part A is associated with 1
Whole
PA
Object diagram W
PA
PB
W PA PB W
PA W PB
PA
W W
PA 26
Composition Class
B is a permanent part of A Relation
A contains B Hints
A is a permanent collection of Bs
Subclass / Superclass
A is a kind of B
A is a specialization of B
A behaves like B
Association (Collaboration)
A delegates to B
A needs help from B
A invokes service of B.
27
Class Diagram Inference Based on Text
Analysis
(based on Dennis, 2002)
A common or improper noun implies a class e.g.
Book
A proper noun implies an object (instance of a
class): CSE Dept, OOSD, etc.
An adjective implies an attribute e.g. price of book
A “doing” verb implies an operation (method)
Can also imply a relationship e.g. student issues Book
A “having” verb implies an aggregation relationship
An adverb implies an attribute of an operation e.g.
fast loading of image… 28
Identify Class Relations
Faculty & student
Hospital & doctor
Door & Car
Member & Organization
People & student
Department & Faculty
Employee & Faculty
Computer Peripheral & Printer
Account & Savings account 29
Identify Classes & Relations
A square is a polygon
Shyam is a student
Every student has a name
100 paisa is one rupee
Students live in hostels
Every student is a member of the library
A student can renew his borrowed books
The Department has many students
30
Identify Classes & Relations
A country has a capital city
A dining philosopher uses a fork
A file is an ordinary file or a directory file
Files contain records
A class can have several attributes
A relation can be association or generalization
A polygon is composed of an ordered set of
points
A programmer uses a computer language on a
project
31
32
The B.Tech program of IITKgp Computer
Science Department:
comprises of many B.Tech batches.
Exercise
Each B.Tech batch consists of many B.Tech students.
CSE Department has many listed courses.
A course may be offered in either spring or Autumn
semesters
A course is either listed as an elective course or a core
course.
Each B.Tech students need to credit between 30 to 32
course offerings.
A student might repeat a course if he/she desires
33
Model Solution
Course Course
List * 30..3 credits
1 2
Core Electiv Course
e Credit
34
34
State Machine Diagrams
35
Stateless vs. Stateful Objects
State-independent (modeless):
Type of objects that always respond the same
way to an event. Lamp
Lamp
On
On
on
off on
State-dependent (modal): Lamp
Lamp off
Off
Off
Controller classes are an important class of
statefull examples:
A controller may change its mode depending on sensor
inputs and user inputs. 37
Stateful Classes
In a client-server system:
Servers are stateless, clients are stateful.
Common stateful objects:
Controllers:
A game controller may put the game in expert,
novice or intermediate modes.
Devices:
A Modem object could be dialing, sending,
receiving, etc.
Mutators (objects that change state or role)
A RentalVideo is rented, inStore, or overDue
38
Event-Based Programming
Traditional programs have single flow of
control:
Represented using flowchart or activity diagram
Event-driven systems :
In contrast, depending on an event
occurrence, corresponding handler is
activated
Programming these using traditional approach is
not suitable, and would at the least cause wasteful
computations.
Represented using state machines. 39
What Kind of Behavior?
In general, state machines are suitable:
For describing event-driven, discrete
behavior
Inappropriate for modeling continuous
behavior
time
40
Why Create A State Model?
Tackle complexity
Document:
For review, explaining to others, etc.
Generate code automatically
Generate test cases
41
Finite State Automaton
A machine whose output behavior is not only
a direct consequence of the current input,
But past history of its inputs
Characterized by an internal state which
captures its past history.
ON
OFF
42
Basic State Machine Diagram
Graphical representation of
automata behavior…
on
Lamp On
on
off
off
Lamp Off
43
Outputs and Actions
Automaton generates outputs during
transition.
Alternate representations.
on
on Lamp On
Lamp
On display(”on”)
off off
Lamp Lamp
Off Off
duration
45
Event ExamplesSignal event
collision
Move Stop
state transition
state
startAutopilot(normal)
Manual Automatic
Call event
when(11:49p
m)
Time event
CapsLo
Caps Unlock cked
AnyKey/
Send-upper-
48
Case-code
Exercise 1: State Machine Diagram of a
Library Book
•A library book to start with, is present in a shelf…
•When borrowed out, it is not on shelf…
•Returned, on shelf…
initial state
state
On shelf
final state 49
Exercise 2: Construct State Model
A car is in idle mode when ignition is off:
Changes to initial mode when ignition is keyed
ON.
The car accelerates when the acceleration pedal is
pressed.
Cruise
Controller
While accelerating, the car goes into a cruise mode,
as soon as cruise switch is set to ON.
Cruise mode is turned off either when brake is
applied or the cruise switch is turned off
Cruise mode can be resumed by setting cruise switch to
ON.
mode.
Cruise Controller
Ignition
Acccel Pedal
Off
Pressed
Cruise
Cruis Switch
Cruis e OFF
e Switc
Switc h ON
h ON Cruising
51
Exercise 3
Model a keyboard using UML state
machine diagram:
52
Solution
/n=0
Defau KeyStroke
[n=100,000]
lt
keyStroke/
n++, transmit code
Broken
53
Exercise 4: Draw State Machine: GUI
Accepts only Balanced Parentheses
(
Balanced Not
Balanced
star
t end )
* *
Inputs are any characters
No nesting of parentheses
No “output” other than any state change
54
Example 5: Draw State Machine: GUI Accepts
only upto 3 Nested parentheses
end
( ( (
55
How to Model Nested
parentheses?
(/count++
(/count=1
star OK Wait
t
)[count==1] /count=0
end )[count>1]/
count--
A state machine, but not just a state
machine --- an EFSM
56
Extended State Machines
Addition of variables (“extended”)
Lamp
Off
57
UML State Machine
Model
58
State Chart Diagram
FSMs suffer from a few severe shortcomings:
What are the shortcomings of FSM?
State chart is based on the work of David
Harel [1990]:
Overcomes important shortcomings of FSM
¯
Extends FSM in 2 major ways: Concurrent
states and hierarchy.
59
Robot: State Variables
Power: On, OFF
Movement: Walk, Run
Direction: Forward, Backward,
left, Right
Left hand: Raised, Down How many
states in the
Right hand: Raised, down state machine
model?
Head: Straight, turned left, turned right
Headlight: On, Off
FSM: exponential
Turn: Left, Right, Straight rise in number of
states with state
variables 60
Event State
turnOn Activated
turnOff Deactivated (Idle)
stop Stopped
walk Walking
run Running
raiseLeftArm LeftArmRaised
lowerLeftArm LeftArmLowered
lowerLeftArm LeftArmLowered
raiseRightArm RightArmRaised
lowerRightArm RightArmLowered
turnHead HeadTurned(direction)
61
speak Talking(text)
State Chart Diagram Cont…
State chart avoids two problems of FSM:
State explosion
Lack of support for representing
concurrent states
A hierarchical state model:
Makes use of composite states --- OR
and AND states.
62
Features of State Charts
Two major features introduced :
Nested states S1
S2
Concurrent states
Nested State
Several other features
have also been added:
History state s11 s21
Broadcast messages
Actions on state entry and exit s12 s22
… Concurrent State
63
Nested State Diagrams
Hierarchical organization
is a classic way to control
complexity:
of programs superstate
of documentation
of objects
…
Why not state diagrams?
superstates
substates
substates 64
State Chart Diagram
Cont…
Basic elements of state chart diagram:
Initial State: A filled circle
Final State: A filled circle inside Alar
Off
a larger circle m
State chart in UML is called state
machine:
As it not only models state behavior but 65
State Machine Diagram
State machine is the code that
implements a model and runs on a
computer.
In contrast, a state chart is a
description of a state machine,
66
UML State Machine Diagram: Syntax
A state is drawn with a
round box, with three
compartments for: Name sometimes
name state variables
left out when
empty
state variables actions
actions performed
A transition is drawn
with a labeled arrow,
event causing the
transaction
AnEvent [guard] / SomeAction
guard condition
Action to perform 67
68
Syntax of UML State machine
71
Basic UML State Model Syntax
“top” state
State
Initial
pseudostate Top
Trigger
Ready
Transition
stop /ctr = 0
Done
Final
Action
state
stop
72
Guards
Boolean predicates to indicate Conditional
execution of transitions
bid [value < 100] /reject
Unhappy
73
Eliminating Duplicated Transitions
Duplicate transitions
usually exist when some
transition can happen
from every state:
“error” Quit
“quit”
“abort”
These duplicates can be
combined into a single
transition:
A transition from a Quit
superstate holds for
all of its substates!
74