You are on page 1of 60

• To implement in Java: Association: Java

Implementation
– Use a reference variable of one class as
an attribute of another class

EL
Bookname: OOSD
abook Author: Gamaa
ISBN: 12234434
Book Reference

PT
Book instance
member5
Bookname: abook
memberName: AKK
Member Number: 412323
N
Member
1 Borrowed by 1
Book

1
Implementing Association Multiplicities
• Fixed multiplicity is straightforward:
1 Borrowed
The reference field would be Member
by 1..10
Book

EL
Book [] book=new Book[10];.
• When the upper end is *:

PT
– Java collection classes can be used
N
– Collection classes were added to Java as a
part of JDK 1.2

2
• When an association-end multiplicity is Java
*, need to use Java Collections. Collections
• Collection classes were added to Java as

EL
part of JDK 1.2
• Operations supported:

PT
– Add
– Remove N
– Access individual objects (Iterators)

3
Java Collections
• Java collection classes are of three
basic types:

EL
– List (Ordered)

PT
– Set (Unordered)
N
– Map (Key-value pairs)

4
• Before Java SDK1.2, Java provided a handful Bit of
History…
of data structures:
–Hashtable

EL
–Vector, etc.
• These were useful and easy to use:

PT
–But were not organized into a framework.
N
• In SDK1.2 legacy data structures retrofitted
to the new model.

5
«interface» «interface»
Collection Map

«interface»
«interface» «interface» «interface» SortedMap
Set List Queue

EL
PT
HashSet «interface» Vector ArrayList LinkedList TreeMap HashMap
SortedSet

Linked TreeSet
N
HashSet

6
Java Collections: What is it?

“The Collections Framework provides


a well-designed set of interfaces and
classes for storing and manipulating

EL
groups of data as a single unit, a

PT
collection.”
-java.sun.com N
7
• List : Sequences Basic Java Collections
– Ordering is implicit
– it is legitimate to ask questions like “what is the first object in the
sequence?”
– Add book as first book etc.
• Sets: Unordered collection

EL
• For all Collection classes:
– Can create an Iterator object to access each item in the collection once.

PT
• Maps: Qualified associations
– Each entry involves a pair of objects.
– A map is also called as a dictionary.
N
– it is legitimate to ask questions like “what object- if any - is associated
with the following key?” or
– “does this map contain the following key?”.

8
• LinkedList: Which List to Use?
– Good if the list changes size (grows or
shrinks) frequently
– Good for accessing either end of the list, but

EL
slower when accessing items in the middle of
the list

PT
• ArrayList:
N
– Good if accessing elements by specific
position, but slow for adds and removes.

9
Vector class
• In what ways different from ArrayList?
• Similar to an ArrayList, but synchronized for
multithreaded programming.

EL
• Mainly for backward-compatibility with old

PT
java.
• Used also as base class for Stack
implementation. N
10
class Customer{ Code for
Association
private ArrayList <Account> accounts = Multiplicity
new ArrayList<Account>();
public Customer() {

EL
Account defaultAccount = new Account();

PT
accounts.add(defaultAccount);
}
} N
Customer 1
has
1..* Account

11
Home Work: Write Code for Example
Association Relationships

1 borrowed by *

EL
Library Member Book

PT
Employee * N
employed by 1
Company

12
Association Class

EL
PT
N
13
• An association relation between classes
often has its own attributes and methods: Association
Class
– Example 1: A teacher teaches a subject:
• A teacher may teach the same subject multiple
times over many semesters

EL
• Each time the students may be different
– Example 2: A person works for a company

PT
• The date he joined a company

N
• Pay scale and grade at which joined, promotion,
so on
• He may even join the company multiple times

14
• An association class is shown as Association Class
a class symbol:
– Attached to the association *
symbol by a dashed line. Teacher Subject

EL
• An association class: Teaching

PT
– Same name as the association
relation because...
N
– It represents the association!

15
Connection
Association
Server 1 * Client Class: Example 1
Connection
baudRate

EL
protocol
total Cost
Disconnect • These attributes don’t

PT
reportUsage belong to either the Client
rerouteLink or Server class.
• They are attributes of the
connection itself.
N
• An association class can have methods as well as attributes.

16
* *
Person Skill
An association class is a
Association “normal” class, and may

EL
Class: Competency
include attributes,
Example 2 methods, relations,
inheritance etc.

PT
level
date acquired
How many
association display()
class objects? N
17
Implementing Association Class
*
Subject Student Subject Student
1
Registration * Registration
Class Diagram Mark: Integer Class Mark: Integer
Diagram

EL
OOSD A A
OOSD
:Registration

PT
:Registration
Mark = 81 Mark = 81

Object
Diagram
:Registration
Mark = 85
N B

Object
:Registration
Mark = 85
B

Diagram

18
public class Subject { Java Code
private ArrayList <Registration> reg=new ArrayList<Registration>();
public void enrol(Student st) { Pass the Student
reg.add( new Registration(st) ); to Registration.
}
Module Student

EL
... Maintain the link to
} Registration Registration 1
*
class Registration { Mark: Integer

PT
private Student student;
private int mark;
Registration(Student st) {

}
...
student = st; mark = 0;
N Keep track of the
Student reference.
}

19
Association Class: Example 4
RealEstate 1 *
Developer Client

EL
Contract

PT
An association class is a
“normal” class, and may Amount
Contract #
include relations,
inheritance etc. N Date
display()

20
public class RealEstateDeveloper{
private Vector <Contract> contracts= new Vector <Contract>();
public void buy(Client c){contracts.add(new Contract(c))};
}
public class Client{

EL
private Address address;
public Address getCurrentAddress(){}

PT
}
public class Contract{
private Client client;
private int contractNo;
N
public Contract(Client c){ client=c;}
} 21
• An object of an association class: Ternary
Association
– Stores the details of one link for two or more
associated class.

EL
• Some times three (or more) classes may be
associated:

PT
– In this case an association end represents the
N
potential number of values at that end when the
values at the other end is kept fixed.

22
Ternary Association
Man 1 1 Woman

EL
and we can marry

PT
add more 1..3
classes to the Priest
diamond… N
23
Implementation of Ternary Association
• Implementation of ternary association.
– Decompose it into a set of binary associations.

EL
Man 1 1 Marriage 1 1 Woman
Participates in

PT
Participates in
* Performed by
1..3
N Priest

24
Record
As association arity increases,
Goals implementation complexity
increases… We shall exclude from
our discussions 3ary and higher-
Player 11 1 Team ary associations…

EL
PT
*
Season N
25
Association: Quiz
Book Editor
title: String * 1 name: String
Edited by
editor: String myBooks: Book

EL
What is wrong?

PT
1. Association denoted by symbol not attributes.
– Implementation (LinkedList, ArrayList, arrays, vectors, ids

N
etc) is left to the detailed design phase.
2. Wrong arrow type

26
Qualified Association

EL
PT
N
27
 A qualified association allows us to express Qualified Association
uniqueness Class belongs Student
*
 Implemented by hash tables, maps, dictionaries.
1 0..1
Class Student

EL
Roll

1 0..1

PT
Directory file
name File

 How to read?
 N
There exists upto one file for each instance of
filename in the directory .

28
• Consider an order has many Order lines. An Example
1 *
Order Has Line item Order Line

EL
• Let us express: There is at most one Order Line in the
Order for each instance of Product.

PT
1
0..1
Order Product
N
Line item Order Line

29
Qualified Association…
League 1 * Player
nickName

EL
1 0..1

PT
League nickName Player

•The second conveys more information…


N
•Hint on implementation…

30
Qualified Association: Implementation
1
League nickName 0..1
Player public class Player {
private League
public class League { league;
private Map players=new HashMap();

EL
}
public void addPlayer

PT
(String nickName, Player p) {
if(!players.containsKey(nickName))
} N
players.put(nickName, p);
}

31
Converting to Qualified Association

Person employee
works for
employer
Company
* 1
Assume company assigns each employee a unique empId.

EL
Give qualified association representation…

PT
employer
employee
Person 0..1 works for
empId Company
N 1

32
Qualified Association
1
Bank accno 0..1 Account

• Qualifier hints at setting up efficient

EL
access to linked objects:
– For example, access accounts based only

PT
on the account number;
N
– Also to avoid a linear search through all
accounts.

33
Summary of Implementation of Association
• 1-to-1 association:
– Role names become attributes

EL
• 1-to-many association:

PT
– Translate into a Vector or ArrayList
• Qualified association:
N
– Translate into a Map or Hash table

34
Overdoing Associations
PersonInfo
• Avoid unnecessary Associations
Name
Address
PersonInfo E-Mail
Person 1 1

EL
Birthday
Address
Name E-Mail
Birthday Do This

PT
Avoid This…
N
35
Relation Class
Relationships
Generalization Association Dependency

EL
Binary Association N-ary Association

PT
Aggregation

N
Composition

36
• Represents whole-part relationship Aggregation
• Represented by a diamond symbol at the Relationship
composite end. Company
employs
Person Club
* * memberOf 1

• Usually creates the components:

EL
– But often indistinguishable from plain association.

PT
– Except, aggregate usually invokes the same
operations of all its components.
N
• Usually owner of the components:
– But can share with other classes

37
Aggregation:
Document
1
* Paragraph Line Examples
1
*

EL
1 * 1 Club
* Person memberOf
Company

PT
employs

N
38
Aggregation cont…

 An aggregate object contains other objects.

 Aggregation limited to tree hierarchy:

EL
− No circular inclusion relation.

PT
*
Paragraph
N
*
Line

39
• A stronger form of aggregation Composition
– The whole is sole owner of its part.
• A component can belong to only one whole

EL
Circle
– The life time of the part is dependent Point

PT
upon the whole.
Circle 1 Point
Polygon
N 3..*

40
Composition Relationship
• Life of item is the same as that of order…

EL
1
Order * Item

PT
N
41
Composition:
Car Alternate
Notation
4 1
Wheel Engine

EL
2 1
Door Chassis

PT
1 1
Axle N Steering

42
• An object (component) may be a part of ONLY one
composite at a time. Composition
Whole is responsible for the creation and disposition of its parts.

EL
Window whole

PT
1
*
Frame
N part

43
• Composition: Aggregation vs.
Composition
– Composite and components have the same life line.
• Aggregation:

EL
– Lifelines are different.
• Consider an order object:

PT
– Aggregation: If order items can be changed
N
or deleted after placing order.
– Composition: Otherwise.

44
Order
1
* Item
Composition Composition versus

EL
Aggregation

PT
1

Order * Item
N
Aggregation

45
public class Car{ Implementing
private Wheel wheels[4]; Composition
public Car (){
wheels[0] = new Wheel();

EL
wheels[1] = new Wheel();
wheels[2] = new Wheel();

PT
wheels[3] = new Wheel();
}
} Car
N 1 4
Wheel

46
import java.util.ArrayList; Implementing
public class CarShop{ Aggregation
private ArrayList<SalesPerson> people = new
ArrayList<SalesPerson>();

EL
private ArrayList<Car> cars = new ArrayList<Car>();

PT
public addCar() {
cars.add(new Car());
* Car
} Car ShopN 1
Sales
* man
47
Inner Classes Translation public class Person {
private Name name;
•If house is used only in private House house;
the Person class: ...
class House {

EL
–It is usually declared as ...
an inner class in }

PT
}
Person.
Person
N
* House

48
How to identify composition relationship?
• Lifetime of part is within lifetime of composite
– There is a create-delete dependency
• There is an obvious physical or logical assembly

EL
• Some properties of composite propagate to parts

PT
(e.g., location)
N
• Operations applied to composite propagate to
parts (e.g., destruction, movement, recording)

49
Class Dependency

Dependent Class Independent Class

EL
PT
N
50
• Dependency relationship can arise due to a variety of reasons:
– Stereotypes are used to show the precise nature of the dependency.
Type of Stereotype Description
dependency Dependency
Abstraction «abstraction» Relates two model elements, that

EL
represent the same concept at
different levels of abstraction
Binding «bind» Connects template arguments to

PT
template parameters to create model
elements from templates.
Realization «realize» Indicates that the client model element

Substitution «substitute»
N is an implementation of the supplier
model element
Indicates that the client model element
takes place of the supplier.
• Dependence are commonly caused by:
– Local variable Dependency
– Parameter
– Return value

EL
Class A { A B
B Foo(B x) {

PT
B y = new B();
return y;} N
}
52
Dependence – Possible Implementations
class DependentClass{
DependentClass
void myFunction1(
myFunction1()
myFunction2() ReferencedClass r ) {..}

EL
myFunction3()
referencedClass myFunction2(

PT
dependence .. ) { .. }
arrow
void myFunction3( .. ){
ReferencedClass
N}
ReferencedClass r; ..}

53
Association Vs. Aggregation
• Is aggregation an association?

EL
• Is composition an aggregation?

PT
N
54
• aggregation: "is part of" Car
1
– Symbolized by empty diamond 1 aggregation
1
• composition: “is made of” Engine

EL
– Stronger version of aggregation Book
– The parts live and die with the whole 1
composition

PT
– Symbolized by a filled diamond *
Page

• dependency: Depends on…


N
– Represented by dotted arrow.
dependency
Member Book

55
Aggregation Composition

Author SalesOrder

EL
1..5

PT
*
Book
*
LineItem
N
56
•One Whole aggregates 5 PartA Whole Multiplicity Quiz #1
•One Part1 is part of 1 Whole
1 3
Draw Class diagram 5 2
PartA PartB

EL
•One Whole aggregates 2 PartB
•One PartB is part of 3 Whole

PT
P1 Object diagram
P1 W
W P1
P1
W
N Pn
Pn Pn W

P1 W

57
• Composition
– B is a permanent part of A Class Relation Hints
– A contains B
– A is a permanent collection of Bs
• Subclass / Superclass

EL
– A is a kind of B
– A is a specialization of B

PT
– A behaves like B
• Association (Collaboration)
– A delegates to B N
– A needs help from B
– A and B are peers.

58
• A common or improper noun implies a class e.g. Book
• A proper noun implies an object (instance of a class): Class Diagram
CSE Dept, OOSD, etc. Construction
• An adjective implies an attribute e.g. price of book Based on Text
Analysis
• A “doing” verb implies an operation (method)

EL
– Can also imply a relationship e.g. student issues Book

PT
• A “having” verb implies an aggregation relationship
• A predicate or descriptive verb phrase elaborates an
N
operation e.g. ISBN numbers are integers
• An adverb implies an attribute of an operation e.g.
fast loading of image…
59
 Faculty & student
 Hospital & doctor
Identify Class Relations
 Door & Car
 Member & Organization

EL
 People & student

PT
 Department & Faculty
 Employee & Faculty
N
 Computer Peripheral & Printer
 Account & Savings account

60

You might also like