Vous êtes sur la page 1sur 85

Object Oriented Analysis

& Design
Object

Oriented Systems Analysis and


Design Using UML, McGraw Hill, 2002. By
Bennett, McRobb and Farmer

8/26/03

Course Covers 3
Issues

Object Oriented Development


Process
e.g USDP

Usage of UML notation


e.g Usecase Model

Object Orientation- basic concepts


e.g encapsulation, inheritance
2

Week -1 : Discussion Points


Based on Chapter 4 & 5 of B,M&F
Evolution of object-orientation
Abstraction
OO approach- Advantages
UML- an introduction
Objects- basic concepts

Aim of Software Engineering


Produce

Quality Software
Less effort (easy
development
process)
Less cost and time

Quality Software ?
Reliable
- Reusable
Robust
- Maintainable
Efficient
- Userfriendly, etc.
8/26/03

Object Oriented Paradigm


OO

Analysis

OO

Design

OO

Programming

OO

Database

8/26/03

Evolution - to OO
Approach
Early machine- single programmermachine code & assembler
Next level machines- High level
programming
Moderate machines- program groups
GOTO - structured programming
Efficient machines- Structured Design
and Analysis methods
6

Evolution- to
OO
Very efficient machines
demands very complex systems
efficient methodologies - O-Oriented, ?
case tools
programming environments
reusable components, etc.

In each stage in the evolution the


level of abstraction increases

Abstraction
Focus only on essential issues
Ignores unnecessary detail Tiger
E.gs

All are
Human Bones Nerves Heart

When Sam returned the book in red shirt the


computer displayed the fine.
How 40 million transistors and other devices powered
by electricity collaborate to determine the fine?
8

Unified Software Development


Process

Other models; Water fall, SDLC, SPIRAL


Embodies best practices in SE

Requirements-driven development
Component-based development
Architecture-centrism
Visual modelling techniques

Adopts iterative and incremental


approach
4 main phases
5 main workflows
9

USDP
Phases
Inception
Elaboration
Construction
Transition

Work Flows
Requirement Capture
Analysis
Design
Implementation
Testing

Each phase may have several iterations


Use UML models in all phases

10

Within each phase activities are grouped into work-flows


Inception

Project
Phases

Elaboration

8
Iterations
within each
phase

Requirements

The balance
of effort
spent in
each
workflow
varies from
phase to
phase

Analysis

Design

Implementation

Test

Workflows

Transition

Construction

Size of
square
relative to
time spent
on
workflowh

Within phases there may be more than one iteration

11

Two main OO characteristics

Object level Abstraction

In Structured Mtds, modular level


abstraction only

accNo

module

viewBalance

balance

Seamless Transition between phases

In Structured Mtds, ER, DFD to Structure


Chart, etc.
12

Two main Advantages


Good

Quality software

Easy

development
process
13

Object level Abstraction

Objects in process resembles realworld objects - conceptually similar


ideas

Object is a self contained package


manipulated using well-defined
interface (e.g. myAccount.viewbalance(
Object
)) viewBalance()

myAccount

14

Seamless Transition

Same vocabulary in all phases


objects

No need to transform models, just


incrementing through iteration

Final product is just a collection of


objects interacting in certain manner
15

Structured Vs OO approach
Structured
Account

amount
message

aNo

withdraw

amount

message

withdrawal

balance
Account

ER

OO approach
Objects

DFD with Data Store

Structure Chart

MyAccount::
aNo= 101
balance=500

withdraw(X)

:MyAccount

balance( )
withdraw( )
--16

Easy Development Process why?

Problem domain is well understood


productivity increased

Good communication between stake


holders
reworking reduced

Use of reusable objects


reinventing avoided

17

Easy Development Process why?


Objects are easy to modify, or
extend
Reduce project size as redundancy

avoided

Easy transition between phases


Test time reduced

In general, cost, time and work


reduced
18

Good Quality Software why?


Evolves around known concepts - good
communication- less errors
Almost no errors in transition process
Reliability due to reusable SW
components
Reliability due to encapsulation
Less coupling between sub-systems
Encourage good programming practices

19

UML have several models -Why


Model?
A model can represent real or
imaginary things from any domain
A model is quicker and easier to build
A model can be used in a simulation
A model gives good abstraction

20

Model
A model follows standards
A model provides a complete view of a
system from a particular perspective.
A model may consist of a single
diagram or consist of many related
diagrams and supporting data and
documentation.

Eg. Usecase model in UML consist of Usecase diagram and use-case descriptions

A model can evolve


21

UML- an introduction

UML is not a SW development methodology


methodology may also define input, process,
output and management issues for each phases
USDP is a methodology based on UML

UML is a graphical modeling language


has a collection of well-defined techniques and
notations
to model SW structure, behavior & organization

UML is a standard language


adopted by OMG in 1997 (www.OMG.org)
22

More on UML

UML consists of many best engineered


practices
already tested in complex projects by its
developers- Booch, Jacobsen & Rumbaugh

UML is used to Specify, Visualize,


Construct, and Document the artifacts of
SW system
UML assumes use-case driven, architecture
centered, iterative and incremental process

23

Diagrams in UML

Activity
diagram

UML diagrams are well defined in


the UML specification.
Write Chapter

E.g. use case diagram

Plan Chapter

Produce
First Draft

UML diagrams consist of:

icons
two-dimensional symbols
paths
Strings

Revise Draft

[not satisfied]
[satisfied]
Add Exercises

Add References
to Bibliography

There are 9 types of diagrams in UML


24

Author

Activity
Diagram
An Example:
Activity
diagram of the
tasks involved
in producing a
book.
Using Swimlanes

Reviewer

Typesetter

Printer

Write Chapter

Review Chapter

Revise Chapter
[book not
complete]
[book complete]

Typeset Book

Correct Proofs

Reset Book

Print Book

25

System- 4+1 view in UML

Different models present different


views of the system, for example:

logical view
process view
implementation view
deployment view
And
use case view

(UML&UP by Arlow, J. pg 19)


26

UML- Models and Views

Structural Modelling
Static View ( Class Diagram)

Behavioural Modelling
Functional View (Use-case , Activity
Diagrams)
Dynamic View (Interaction Diagrams sequence and collaboration)
Temporal View (State Chart)

Architectural Modelling
Implementation view (Component Diagram)
27
Configuration view ( Deployment Diagram)

Examples of some UML


Models

Requirements Model
complete view of requirements
may include other models, such as a Use Case
Model - includes textual description as well as sets of
diagrams

Behavioural Model
shows how the system responds to events in
the outside world and the passage of time
an initial model may just use Collaboration
Diagrams and a later model will include
Sequence Diagrams and State charts

28

Iteration on Use Case Model


Staff Management

Iteration 1
Obvious use cases.
Simple use case descriptions.

Add a new staff


member
Staff Management

Add a new staff


member
Add a new staff
grade

Add a new staff


grade

Accountant

Change the
rate for a
staff grade

Change the
rate for a
staff grade

Change the
grade for a
staff member

Accountant
Change the
grade for a
staff member

Calculate staff
bonuses

Calculate staff
bonuses

Staff Management

Add a new staff


member
Staff Management

Iteration 2
Additional use cases.
Simple use case descriptions.
Prototypes.
Iteration 3
Structured use cases.
Structured use case descriptions.
Prototypes.

Add a new staff


member
Staff Management
Add a new staff
grade

Campaign Selection

Add a new staff


member
Add a new staff
grade

Add a new staff


grade
Accountant

Accountant

Change the
rate for a
staff grade

Change the
grade for a
staff member

Holborn Motors
Lynch Properties
Holborn
Motors
Yellow
Partridge
Yellow
Partridge
LynchZeta
Properties
Systems
Holborn
Motors
Yellow
Partridge
Yellow
Partridge
Spring Jewellery Campaign 1997
Properties
Systems
Campaign:LynchZeta
Spring Jewellery Campaign 2001
Yellow Partridge
Spring
Jewellery
Campaign
1997 2002
Spring
Jewellery
Campaign
Zeta Systems
Campaign:
Spring
Jewellery
Campaign
2001
Summer
Collection
1998
Spring
Spring Jewellery
Jewellery Campaign
Campaign 2002
Campaign:
2002
Summer Collection 1998
OK
Quit

Client:
Campaign Selection
Client:

Change the
grade for a
staff member

Change the
grade for a
staff member

Accountant

Campaign Selection

Change the
rate for a
staff grade

Change the
rate for a
staff grade

Client:

Calculate staff
bonuses

Calculate staff
bonuses

OK

Calculate staff
bonuses

OK

Quit
Quit

Campaign Management
Assign staff
to work on
a campaign

include
Campaign Management

Assign staff
to work on
a campaign

Assign staff
to work on
a campaign

Campaign
Manager

Campaign Selection

Find campaigninclude

Campaign Selection

include

Add a new
advert to
include
a campaign

Check campaign

include
Add a new
advert to
a campaign

extend

Print campaign
summary

Print campaign
summary
extend

extend

Accountant

extend

Accountant
Print campaign
summary

Client:

extend

Check campaign
include
budget

extend
Check campaign
budget

Print campaign
invoice

Print campaign
invoice

Holborn Motors
Lynch Properties
Holborn
Motors
Yellow
Partridge
Yellow
Partridge
LynchZeta
Properties
Systems
Holborn
Motors
Yellow
Partridge
Yellow
Partridge
Spring Jewellery Campaign 1997
Properties
Systems
Campaign:LynchZeta
Spring Jewellery Campaign 2001
Yellow Partridge
Spring
Jewellery
Campaign
1997 2002
Spring
Jewellery
Campaign
Zeta Systems
Campaign:
Spring
Jewellery
Campaign
2001
Summer
Collection
1998
Spring
Spring Jewellery
Jewellery Campaign
Campaign 2002
Campaign:
2002
Summer Collection 1998
OK
Quit

Client:
Campaign Selection

include
budget
Find campaign

Campaign
Manager

Accountant

Find campaign

include
Add a new
adv ert to
include
a campaign
Campaign Management

Campaign
Manager

Print campaign
invoice

Client:

OK
OK

Quit
Quit

29

OBJECTS

30

Objects - basic concepts


Based on Chapter 4 of Bennett,
McRobb and Farmer:
Object Oriented Systems Analysis
and Design Using UML, (2nd
Edition), McGraw Hill, 2002.

31

Object- Basic Concepts

Classes and Instances (Objects)


Attributes, Properties and Behaviour
Method, Operation and Signature

Object State , Significant states


Information hiding and Encapsulation

Message-passing and Encapsulation

Generalisation & Specialisation /


Inheritance
Overloading and Overriding

Polymorphism

32

Objects
An object is:
an abstraction of something in a
problem domain, reflecting the
capabilities of the system to
keep information about it,
interact with it,
or both.
Coad and Yourdon (1990)

33

Objects
Objects, an abstraction of a real-world
thing, that have state, behaviour and
identity.
Booch (1994)

State: the condition of an object at any


moment, affecting how it can behave
Behaviour: what an object can do, how
it can respond to events and stimuli
Identity: each object is unique

34

-- abstraction of something in a

domain--

2-Door, Automatic, Red, Honda


Jet, Compression
Mechanic

Public

CAR- in game SW

Vs

CAR - in Insurance SW

ID, speed, color, location

regNo, model, owner, value

draw( ), changeSpeed( )

getValue( ), getOwner( )

In SWD process,
Only
necessary
attributes,
behaviors
and
relationships of objects related to the problem
domain are abstracted
35

Example
Car

My car is a car.
It is not a truck

is an object

Identity my car
State (current )

There are many cars. All have


some things in common

Current state is partially determined by the values of


the properties or the attributes.
RegisterNumber - ? Model - ?, Type - ?,
Color - ?OnOff - ? , Speed - ?, PetrolLeft - ?
Some states are more significant than others.

Behavior
Start, Off, ChangeSpeed(?),
getPetrolLeft( ?)

The characteristics of an object is determined by its properties,


attributes and behavior.
36

My new red car

Identity

Every object in real-world has a unique


identity

Even a drop of water has space and time


parameters.

Identity is not a primary key.

The Primary key may be one of the stable


attributes
Object ID is guaranteed to be unique by
OOP system.
An OID is never reused.

Different objects (which have different


identity) may be in same states.

37

onClaim / completed/ noClaim

State

An object may be in different states


- depending on the values of its attributes and relationships
- not all state variations are significant in a domain.
Some attributes will not change in life-time of an object.
cannot alter states (e.g.engineNo)
What are the significant states for a copy of library book ?

COPY

?
OnShelf

OnHold
OnBind

OnReserve
38

ChangeSpeed(100)

Behaviour

gear=neutral

Objects behave in well-determined way.


current state determines its behavior.
In the other hand, the state of an object may
be changed due to the effects of its certain
behavior.
start( )
CAR

Complete this !

COPY

OFF

onShelf

onLoan

Behaviors are implemented as operations.


39

Class
All objects are instances of some class
Class: a description of a set of
objects with similar

attributes,
operations or methods
relationships and semantics.

An object is:
an instance that
originates from a class, it is structured
and behaves according to its class.
OMG (2001)

40

Class, and Instance


(Object)
The purpose of a class is to declare
a collection of methods, operations
and attributes that fully describe
the structure and behaviour of
objects.

OMG (2001)

Structure: what an object knows,


information that it holds
Behaviour: what an object can do

41

Class and
Objects

Classes are templates for objects.


Every Object is an instance of one and only one
Class in a particular application.
Behaviors are common to all the objects of a Class.
Values of the attributes are usually different for
different objects.
But, values for the class variables are common to
all the objects of a Class (e.g loanPeriod for Staff class ?)

42

Class and Objects - an implementation point

Account
Class
variable

aNo
balance
dayLimit = 200

balance(?)
withdraw(X)

SamAcc::
aNo=101
balance=500

balance( )
withdraw( )
---

Name of
Class
Data
Declaration
Methods
Definition

instances

SamAcc::Account
aNo = 101
balance = 500

Name of
Object

MicAcc::Account

Data Values

aNo = 105
balance = 600

Name of
Object
Data Values
43

Information Hiding in real


Objects
Obtain services only from its interface

Unnecessary information is hidden

e.g Car- brake / petrol-meter

VCR

Advantages
Easy to use
More Reliable
Reduce Coupling

pause

44

Encapsulation
-3 advantages ? )

easy to use
more reliable
less coupling

Information hiding is implemented as encapsulation in


SW objects
Everything related to an object, data and methods (or
attributes and behaviors), are packaged together.
Methods of other objects cant access its data in principle.

Object is only accessible through its interface.


Account
aNo
balance
balance( )
withdraw( )
---

Name of Class
Data
(usually hidden)

Methods
(usually interface)

balance(?)
withdraw(X)

My Account::
aNo=101
balance=300

45

Message-passing
Encapsulation protects ad-hoc object
access
For each class legal interface is given in
order to get its services (public methods)

Object without interface is . . .?

Several objects may need to collaborate


to complete a certain task. (eg.
returnBook() )
Messages are sent to objects, not to classes.
46

Interloan

Messageuser
library
passing
Client object request a service from a
request

methods

service

server object by sending a message

This server object may in turn need to send


further requests to other objects
But, client need not to know how server
serves
Client should know legal format of the request
(Signature of the method)
ATM-UI::
transfer( )
message

MyAccount::
withdraw( )
method

deposit( )

message
aNo

balance

47

Message-passing and
Encapsulation
Layers of an onion
model of an object:

Message from another object


requests a service.

Operation called only via valid


operation signature.

An outer layer of
operation signatures
gives access to middle
layer of operations
which can access
inner core of data

Data accessed only by


objects own operations.

An objects data
is hidden
(encapsulated).

48

Reusability: OO Vs Structured approaches


Account
aNo

amount
withdraw

message

amount

message

withdrawal

balance
Account

ER

DFD with Data Store

Can we separate ER, DFD,


and Structure chart together
from other parts and use it in
other applications?

Which is more
reusable?

Account
aNo
balance
balance( )
withdraw( )
---

Structure Chart

Class &Object

withdraw(X)

MyAccount::
aNo=101
balance=300

49

Generalization and
Specialization
Classification is hierarchic (disjoint and
transitive) in nature
It is an outcome of natural abstraction
For example,
a person may be an employee, a
customer, or a supplier

An employee may be paid monthly, weekly


or hourly

An hourly paid employee may be a driver, a


cleaner, a sales assistant
50

Specialization
Hierarchy

Abstraction

Person

Employee

monthly
paid

More general
(superclasses)

Customer
weekly
paid

Driver

Cleaner

Supplier
hourly
paid

Sales
assistant

Real-world entities on leaves

Subclasses are fully


Consistent with super
classes and add more
information

More specialized
(subclasses)
51

Super class Vs Sub


class
More general/common bits of description are
abstracted out from specialized classes:
General (superclass or base class)

Person
Name
Date of birth
Gender
Title

age ( )

Specialized (subclass)

HourlyPaidDriver
StartDate
StandardRate
OvertimeRate
LicenceType
52

G&S is a IS-A / IS-A-KIND


relationship

Student is a person.
Whatever true for a person is true for a student.
Student is a special type of person.

Anti-symmetric and Transitive


A person may not be a student.
Internal student is a person.

There is no multiplicity constraint.

extramural internal

A student is a n-times person (wrong)


Cannot be instantiated by links(person
abstract).
53

is

Inheritance - an G&S

implementation
The whole description of a super or base

class, including information structure and


behaviour, applies to all of its subclasses.
Loosely, inherited to its children.
Actually, inheritance is one of the facility in
O-O languages to implement G&S
It is a static relationship, impose strong
coupling between participating objects
A subclass must be different from its
siblings (same level) in some way.
- Whale is not under Fish, but under Mammals in Animal Taxonomy
54

Inheritance - an example
Savings class now
have, 4 attributes and
3 methods
MySavings.balance( )

Account
aNo
balance
balance( )
withdraw( )

class variables

will give balance.

withdraw( ) will
be overridden.
Why we need
withdraw( ) in
Account class?

Savings

Current

dayLmt
daySofar
withdraw( )
reset( )

odLmt
withdraw( )

What are the advantages?


55

G&S (or Inheritance) Advantages


Conceptual View

Gives a better understanding of the problem


domain; explicitly shows the differences and
similarities between sub/parent classes

Design View
Increases reusability; properties of the parent class
are passed to subclasses without redefining them.

Global View
Provides extendibility; a well-defined object, even its
source code is not available, may be extended to
suit a particular problem domain. (eg. In Java?)
56

Abstract Classes & Abstract


Methods
A base class is known as an ABSTARCT
class if there is no instance of it.
Account
e.g Account
A method in a base class aNo
balance
is known as an ABSTARCT balance( )
method if there is no codewithdraw( )
in it. e.g withdraw( )
This skeleton will be
Savings
filled later suitably dayLmt
daySofar
in its subclasses withdraw( )

class variable

Current
odLmt
withdraw( )

reset( )

57

More on
InheritanceOverlapping?

Student

Disjoint?

Internal

Member
Staff

Student

Local

Discriminator
Student

Complete?
Student
Asian

type

mode
International
Local

Local

PGrads

UGrads

LocalPGrads
58

Multiple
AInheritance
class may be member

of more than one


hierarchy and it inherits characteristics from
both side ancestors.
Student

Staff
Support Academic

PGrad

UGrad

PGdAcad

What are the complexities?


Multiple inheritance is not supported in some languages.
To get this effect, inherit a subclass from most suitable class
and then include the other parent class(es) as member(s) of it.
59

Poly-morph- ==>Many-form-ism
ism
Poly means many and morph means
forms. One message may be sent to
objects of different classes of a family
Sending object need not to know what
kind of object will receive the message
Each receiving object knows how to
respond appropriately
Jesu
s

Buddah

Pray!
A---

Siva
60

Polymorphism - Examples
resize( x)

<<entity>>
Campaign

Resize Operations

title
campaignStartDate
campaignFinishDate
getCampaignAdverts()
addNewAdvert()

<<entity>>
Campaign

resize( x)

title
campaignStartDate
campaignFinishDate
getCampaignAdverts()
addNewAdvert()

A request to an object of Account family


requestMoney
user

Withdraw()

::ATM interface

Account

Withdraw()
OR
Withdraw()

::Savings
::Cheque

Do you know which account will be used in ATM machine next time ?
Why we need an abstract method withdraw() in Account class ?
61

Overloadin
g

He is noodlesSpoonEating.
He is noodlesStickEating.
He is riceSpoonEating.
He is riceStickEating.
My car is eating petrol

We used to overload words in our life.


Each action needs different approaches,
yet all may be He is eating
In OOProgramming, overloading is an
act of using same name for different but
conceptually related operations.
e.g.
showTime(1 , 5, 12) 01 : 05 : 12
showTime(3912)
01 : 05 : 12
Note that the parameter list is different.

Is it possible
in pascal?
62

Overrriding

An attribute cannot be overriden

Overriding is an act of redefining an


operation
of
a
supperclass
differently in its derived
Accountclass.
no code-skelton

The method withdraw()


Abstract method
inherits
withdraw( )
will be inheritted from overides
Savings to HouseLoan
Savings
amount+daySofar
(this checks daySofar),
< dayLmt
but redefinning
withdraw( )
Amount+ soFar
withdraw() in ChildSa
< Lmt
inherits
ChildSavings
(which instead checks
Lmt) overrides that
withdraw( )
overides
operation.
63

Polymorphism is Run-time polymorphism


Run-time polymorphism

Which method is to be invoked for a request will be


decided at run time. (e.g. withdraw( ))

Sometimes these also called polymorphism.


Ad-hoc polymorphism

Giving same name for conceptually similar but operationally


different methods.
Used mostly within a object. (e.g. showTime( ))

Inherited polymorphism

Methods are inherited to a subclass from its base class.


e.g. balance( )
64

Which is
Polymorphism?
Ad-hoc Same class, different tasks
:Class1.method1(paralist1)
overload
:Class1.method1(paralist2)

Inherited

Run-time

method1(paralist1);
method1(paralist2);
method2(paralist);

Different classes, same task

:Class1.method1(paralist2)
inherit
:Class2.method1(paralist2)

Class1

Different classes, different tasks

Class2
method1(paralist1);

:Class1.method1(paralist1)
Override (which method? - not
:Class2.method1(paralist1)known until run time)
requestMoney
user

withdraw( )

::ATM interface

withdraw()

::Savings

Account
withdraw()

::Cheque
65

An Abstract Class and an Abstract


Account
Method

accNo
balance
balance( )
withdraw( )

public abstract class Account


{
protected int accNo;
protected int balance;
public Account(int an, int b){
accNo = an;
balance = b;
}
public int balance(){
return balance;
}
public abstract void withdraw(int
amount);

Savings
withdraw( )

Cheque
ODLimit
withdraw( )

}
66

Overriding, Inheritance, Reusing


public class Savings extends Account
{
public Savings(int an, int b)
{
super (an, b);
}

Account
accNo
balance
balance( )
withdraw( )
Savings

public void withdraw(int amount)


withdraw( )
{
if (balance > amount)
balance -= amount;
}

Cheque
ODLimit
withdraw( )

}
67

Overriding, Class Variable


public class Current extends Account
{
private static int ODlimit=100;
public Current(int an, int b)
{
Savings
super (an, b);
}
public void withdraw(int amount)
withdraw( )
{
if (balance+ODlimit > amount) balance
-= amount;
}
}

Account
accNo
balance
balance( )
withdraw( )

Cheque
ODLimit
withdraw( )

68

Run-time and inherited


polymorphism
import java.io.*;
public class withdrawCtrl
{
public Account getAccount()throws IOException {
int d =2;
Account A;
if (d==1)
Savings
A= new Savings(100, 1000);
else
A= new Current(120,2000);
return A;
withdraw( )
}

Account
accNo
balance
balance( )
withdraw( )

Cheque
ODLimit
withdraw( )

public void withdraw() throws IOException {


Account A;
A=getAccount();
int amount =100;
System.out.println( A.balance() );
A.withdraw(amount);
}
}

69

Run-time Polymorphism and


Reusability
If we want a Child-Savings
Account that impose a limit
(say 10% of the balance)
on withdrawal amount,
Savings
What we need to do?
withdraw( )

Account
accNo
balance
balance( )
withdraw( )

Cheque
ODLimit
withdraw( )

70

Advantages of
Polymorphism
Conceptually,
it provides

a mechanism to
represent a concept of an act as we percieve it
usually
without giving different names for similar concepts.
Inherent polymorphism supports reusability of
a method.
a base class method may be used in its sub classes
without redifining it.
Run-time polymorphism supports reusability of
a whole object.
can extend an object to suit our requirement.
The withdraw() method could be redefined in
ChildSavings. Therefore, the entire Savings class
71
may be reused.

Objects -More Issues


Object/Class Relationship
Association and Association Class
Multipilicity and other constrains
Aggregation and Composition
Binding, Static Vs Dynamic
Visibility and Accessibility
Meta-class and Class scope attributes
Persistency

72

Relationships(sta

lend

UML

Tom

giveDetail( )

tic)
Objects do not exist in isolation. They need to

interact with each other to perform certain function


The final SW product is a collection of objects and
their interaction is implemented as methods
To interact, objects must have certain relationship.

There are three type of relationships between


classes!

Association
Aggregation (and Composition)
Generalization-Specialization
Dependency relationship will be discussed later.

73

Association

Link
Farmers

worksF
Tom
or
employer
employee

LINK - is a semantic connection between two objects that facilitates message passing.

ASSOCIATION - is a semantic connection between classes, which represents constrains on business

Association

interactions
Link.

is an instance of

bi-directional (direction for name may be shown)


association.
weak an
coupling between classes
compan
navigational direction may be included later y

worksF
0..
0..*
person
or
1*
employer
employee

74

Multiplicit
y

worksF
0..
0..*
person
compan
or
1
employer
employee
y

Role names - may be used with association at both


ends or at one of the ends to increase clarity
manages

Role names are specially important for


reflexive relationships with multiplicity
constraint.

Employee *
person

1
manager

Multiplicity(cardinality) Constrain This constrain


specifies the range of allowable objects that can be
linked with an object of other class under that
association (or on that role).
The format is, lowerbound .. upperbound
75

Other
Constraints
Ordered
Holds must be in some
order

Subset
Manager must be an
employee

XOR
Prevents artificial
subclasses

book

compan
y

Person
Organiz
a

placeO 0..*
n
{ordere
d}

employee
*

{subset
}
manager*

hold

person

account
* perOwne
*
r
{exclusive
account Account
or}
1 orgOwne
*
r
76

Tertiary
Relations

Where can we keep room?

Lecturer
Student

Course
Schedule
room
time

L1 take C1 for S1 in R1
L1 take C1 for S2 in R2

OR
Lecturer
Student

<<ternary>>

Course

Schedule

Another example?

room
time
77

Association class ( usually for m*n


relationships)

account

1..*

UsedFor

If needs some operation or


participate in relationships
with other objects

Attributed
Association
Only used to hold
attributes of a
relationship

student

0..*

Association
class

dateInclude
d

0..*

card

1..*

course

No Name
grade

78

Aggregatio
n

Staff
*

Dependants

*
*

*
Degree

A special form of association that impose wholepart (or is-a-part-of) relationship.


Strong coupling; one end plays more important
role. Not independent.
Holds transitivity and asymmetry properties
A is-a-part-of B, B is-a-part-of C A is-a-part-of C
A is-a-part-of B not B is-a-part-of A

In general, m*n relation is possible. A part may be


a part for many wholes
79

Compositio
n This may be recursive.

Invoice

Drawing

Line

Circle

Invoic-Lines

A special form of composition that demands


strong ownership -a part is not a part of some other
whole - the m*n relationship is not possible (e.g.
book and copy) and
coincident lifetime of part with the whole, that is
part should live and die with whole.
The whole may not behave like any of its parts. It
is not just labeling a group of objects. ( car ? seat)
80

Visibility (of class


members)
3 types
Public (+)
Protected (#)
Private (-).

Account
nextAno
- aNo
# balance
-

+ balance( )
+ withdraw( )

Package ??
Visibility affects the accessibility
of a class member
outside its
boundary

81

Account

Visibility

- aNo
# balance
MySAcc:Savings

balance = balance
amount

nextSAno =5021
aNo = 123
balance = 540
dayLimit = 100
soFar = 25
withdraw( )

---

+ balance( )
+ withdraw( )

MyCAcc:Current
nextCno = 601
aNo = 321
balance = 5640
ODlimit = 1000
withdraw( )

---

If a member is to be used in any of its


subclasses directly, define it as Protected.
But, try to avoid protected and provide a
public method to manipulate that attribute
(e.g. setBalance( ) in Account)

setBalance(balance( )-amount)
82

Binding

The process of determining which process to


be invoked for a certain message call

Static binding
Determined at compile time
Dynamic binding Determined later at run time

Dynamic binding gives flexibility.


Allows the invocation decision to be postponed until
additional information is known.
Which account will be accessed in ATM next,
Service or Current? Which withdraw method is to be
selected next?

X.withdraw( ), depends on X
X is known only at run-time

Swithdraw()

RAM

Cwithdraw()
83

Meta-class and Class scope


attributes

In pure OO environment, everything is an object


A class is also an object, so It must belong to a
class
It is a class of class or meta-class.
Metaclass is an instance of itself.
It is used by the compiler. This handles class
methods (such as new, constructor, etc.)
and class variables, if any.
Class variables (or Class scope attributes) are
shared between all instances of a class.
For example, a class variable may be used to count
the number of objects of a particular class created so
84
far.

Persistenc
e Objects have life-time. They explicitly
created and exist for a period.
Some objects are created during an
execution and destroyed before finish
(e.g. UI objects)
Some objects need to exist beyond
application boundaries ( in a file or DB).
This object must be retrieved in another
session in same state as it was saved.
85