Professional Documents
Culture Documents
Lec 4 (SDA)
Lec 4 (SDA)
Lecture 4
1
Object Associations
• An association relates, links or attaches
different objects
• Example
– Teacher and Computer
– Department and Employees
– Students and courses
2
Types of Associations
• Simple association
• Aggregation
• Composition
3
Simple Association
• A simple association simply relates two or
more objects
4
Example
owns
Teacher Computer
1 1
register
Student Course
n n
5
Aggregation
• This is a stronger kind of association
6
Examples
Vehicle Part
n
Country Region
n
7
Composition
• Composition is a stronger kind of aggregation
– Part-whole relation
– Lifetime binding
– Information hiding
– No sharing
8
Example
Building Room
n
Address
street
city
Emp
province
n country
phone
email
9
class Building {
private:
Room r[10];
...
};
10
Summary
Simple Aggregation Composition
Relationship Yes Yes Yes
Part-whole Yes Yes
Lifetime binding Yes
Information hiding Yes
No sharing Yes
11
Implementation of Association
class Teacher {
private:
Computer* c;
public:
void add(Computer* c) {
this->c = c;
}
...
};
12
Implementation of Association ...
class Computer {
private:
Teacher* t;
public:
void add(Teacher* t) {
this->t = t;
}
...
};
13
Implementation of Association ...
int main() {
Teacher t1(..), t2(..);
Computer c1(..), c2(..), c3(..);
t1.add(&c2);
c2.add(&t1);
t2.add(&c2);
return 0;
}
14
Implementation of Composition
• Two ways
– Using objects
– using pointers
15
Composition using pointers
• Make sure characteristics of “containment by
value”
16
Implementation of Composition
List Node
n
17
Incorrect Implementation of Composition
class List {
private:
Node *head, *tail;
...
public:
void add(Node* n) {
tail->next = n;
tail = tail->next;
}
18
Implementation of Composition ...
class List {
private:
Node *head, *tail;
...
public:
void add(int x) {
tail->next = new Node(x);
tail = tail->next;
}
19
Implementation of Composition ...
~List() {
Node* ptr = head;
while (ptr != tail) {
delete ptr;
ptr = ptr->next;
}
}
20
Implementation of Composition ...
int main() {
List ls, ls2;
ls.add(10);
ls.add(20);
...
ls2.add(..);
return 0;
}
21
Implementation of Aggregation
• Same as that of simple association
22
Question
• Why aggregation?
23
Answer
• Aggregation increases readability
24
Example
NewClass2 NewClass4
Vehicle
NewClass3
NewClass5
25
Example ...
NewClass2 Component
Vehicle
NewClass3
NewClass5
26
Answer ...
• Aggregation provides another form of
abstraction
27
Example
29
Example
Patient Organ
n
30
The End
31