0% found this document useful (0 votes)
11 views49 pages

Lect 10

The document discusses the relationships among classes in object-oriented programming, specifically focusing on composition, aggregation, and dependency. It provides code examples to illustrate these concepts and explains when to use composition versus aggregation. Additionally, it covers class dependencies and the significance of state machine diagrams in modeling behavior.

Uploaded by

ss649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views49 pages

Lect 10

The document discusses the relationships among classes in object-oriented programming, specifically focusing on composition, aggregation, and dependency. It provides code examples to illustrate these concepts and explains when to use composition versus aggregation. Additionally, it covers class dependencies and the significance of state machine diagrams in modeling behavior.

Uploaded by

ss649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Aggregation, Composition,

and Dependence
Relationships Among
Classes

Lect 10
18-02-2025

1
Composition versus Aggregation

1
Order * Item Compositio
n

1
* Aggregation
Order Item

2
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();
}
} 3
Aggregation: Code Example
An aggregation relationship is usually represented as a data field in

the aggregated class.

public class Name public class Person { public class


{ /** Data fields */ Address {
private /* Data fields */
/* Data fields */
ArrayList<Name>
/*Constructors */ name =new
ArrayList<Name>() /*Constructors*/
/* Methods */
; /** Methods */
} }
}
1 * Name
Person 4
*Address
Often Inner Classes are Used


If House is used public class Person
{
only in the
private Name
Person class: name;
private House
 Declare it as an
house;
inner class in
...
Person.

class House {
...
} 5
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 6
Implementing Aggregation: Ex 2

Public class Sentence{ Class Aggregator{


String text; public static void main() {
Sentence(String ){text=s;} BufferedReader br=new
}
BufferedReader(new
Public class Paragraph{
private ArrayList <Sentence> InputStreamReader(System.in));
sentList=new Paragraph p= new
Paragraph();
ArrayList<Sentence>();
public addSentence(Sentence s){ do{
sentList.add(s);
p.addSentence(new
}
} Sentence(br.readLine());
1
Pragraph * Sentence} 7
Deciding Whether to Use Composition or
Aggregation…


Use composition if:
 Lifetime of part is bound within lifetime of
composite

 There is an obvious physical or logical assembly

 Some properties of composite propagate to


parts (e.g., location)

 Operations applied to composite propagate to


parts (e.g., destruction, movement, etc)
8
Class Dependency

Dependent Class Independent Class

Any change to the independent


class would necessitate a change to
the dependent class.

A class may be dependent on


another class due to a variety of
reasons. 9
Dependency

Dependency relationship between two classes X and Y can arise due to a variety of reasons:
 X has an attribute of class Y
 X has a template attribute with a parameter of class Y
 X has a method with an input argument of class Y
 X has a method with an output argument of class Y
 X has of a method containing a local variable of class Y
 Etc.

10
Dependency

Common Dependences are caused by:
 Local variable
 Parameter
 Return value

Example:
Class A { Class B {
B Foo(B x) { …
B y = new B(); …
return y; …
}
} }
11
Dependence – Examples
class MyDependentClass{

void
MyDependentClass myFunction1( MyRefere
att: int ncedClass r ) { .. }
myFunction() MyreferencedClass
myFunction2( .. ) { .. }
dependence
arrow
void myFunction3( .. )
{ MyReferencedClass m
MyReferencedClass
.. }

} 12
Association Vs. Aggregation


Is aggregation an association?


Is composition an aggregation?

13
Summary: Association Types
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
*

 Symbolized by a filled diamond


dependen

dependency: “Depends on” cy
Lotter Rando
 Represented by dotted arrow.y m
Ticket 14
UML Class Relation Notation
Summary
Class
Generalization dependen
Relationship cy

Object Object
Aggregation Composition
Object Association Association Association

1..* 1
n n
0..* 0..*

Will always be “1” 15


Aggregation Composition

Faculty SalesOrder

(team- 1..5 1
teaching
is
possible)
0..* 1..*
CourseTeaching SalesOrderLineItem

16
17
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 18

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 and B are peers.

19
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… 20
Identify Class Relations
Faculty & student
Hospital & doctor
Door & Car
Member & Organization
People & student
Department & Faculty
Employee & Faculty
Computer Peripheral & Printer
Account & Savings account 21
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
22
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
23
24

The B.Tech program of SNU 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

25
Model Solution

BTech BTech Batch


Program
1 *
1
Autumn
*
Stude
Semest nt
er *
Spring
offered in

Course Course
List * 30..3 credits
1 2
Core Electiv Course
e Credit

26
26
State Machine Diagrams

27
Stateless vs. Stateful Objects

Departme
State-independent (modeless):
 These objects always respond the sament
Lamp
way to an event.
Lamp on
On
On

off on


State-dependent (modal): Lamp
Lamp
Off
Off
off

 These objects react differently


to events depending on state orLamp
mode.

Use state machine diagrams to model


objects with non-trivial state behavior.
28
Stateful Classes

Give examples of some classes that have
non-trivial state models:
 Lift controller: Up, down, standstill,…
 Game software controller: Novice, Moderate,
Advanced…
 Gui: Active, Inactive, clicked once, …
 Robot controller: Obstacle, clear, difficult terrain…


Controller classes are an important class of
stateful examples:
 A controller may change its mode depending on sensor
inputs and user inputs. 29
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
30
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. 31
What Kind of Behavior?

In general, state machines are suitable:
 For describing event-driven, discrete
behavior
 Inappropriate for modeling continuous
behavior
threshold There is no support
output

currently in UML for


modeling continuous
behavior

time

32
Why Create A State Model?


Tackle complexity

Document:
 For review, explaining to others, etc.

Generate code automatically

Generate test cases

33
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

34
Basic State Machine Diagram

Graphical representation of
automata behavior…
on

Lamp On

on

off
off
Lamp Off

35
Outputs and Actions

Automaton generates outputs during
transition.
 Alternate representations : Mealy and Moore.
on
on Lamp On
Lamp
On display(”on”)

off on/display(”on”) off on

off off
Lamp Lamp
Off Off

Mealy automaton Moore automaton


36
Event-Driven Behavior

Event types:
 Object interactions:

synchronous object operation invocation (call event)

asynchronous signal reception (signal event)
 Occurrence of time instants (time event)

interval expiry

calendar/clock time
 Change in value of some entity (change event)

Event Instance = an instance of an event (type)
 occurs at a particular time instant and has no

duration

37
38
Event ExamplesSignal event

collision
Move Stop

state transition
state

startAutopilot(normal)
Manual Automatic

Call event

when(11:49p
m)
Time event

Idle after (2 seconds)


Active
39
Exercise 0: Draw State Machine Diagram
of a Keyboard?
•Press any key: lower case ASCII code is
sent to computer…
•Once press the caps lock key: upper
case ASCII code will be sent on a key
press…
Any key/
send-lower-
Case-code Defau Caps Lock
lt

CapsLo
Caps Unlock cked
AnyKey/
Send-upper-
40
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

Returned Borrowed transition


discarde
d
On loan

final state 41
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.

 When ignition is turned off the car goes to idle 42

mode.
Cruise Controller

Initial Ignitio Idle


Idle
n On

Ignition
Acccel Pedal
Off
Pressed

Acceleratin Cruising Break


g off Pressed

Cruise
Cruis Switch
Cruis e OFF
e Switc
Switc h ON
h ON Cruising

43
Exercise 3

Model a keyboard using UML state
machine diagram:
 Transmits key code to computer on each
key stroke.

 Breaks down after entering 100,000 key


strokes.

44
Solution

/n=0

Defau KeyStroke
[n=100,000]
lt
keyStroke/
n++, transmit code

Broken

45
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
46
Example 5: Draw State Machine: GUI Accepts
only upto 3 Nested parentheses

end
( ( (

OK Wait 1 Wait 2 Wait 3


start
) ) )
) * * * ( *
Error
How can we extend this machine to
* handle arbitrarily deep nesting of
parentheses?

47
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 --- it is an EFSM
48
Extended State Machines

Addition of variables (“extended”)

ctr : Integer Lamp


On

off on/ctr = ctr + 1

Lamp
Off

49

You might also like