oosad-uml_lec02-1

85
8/26/03 1 Object Oriented Analysis & Design Object Oriented Systems Analysis and Design Using UML, McGraw Hill, 2002. By Bennett, McRobb and Farmer

Upload: irfan-memon

Post on 25-Dec-2015

9 views

Category:

Documents


3 download

DESCRIPTION

Object oriented analysis

TRANSCRIPT

Page 1: OOSAD-UML_Lec02-1

8/26/03 1

Object Oriented Analysis & Design

Object Oriented Systems Analysis and Design Using UML, McGraw Hill, 2002. By Bennett, McRobb and Farmer

Page 2: OOSAD-UML_Lec02-1

2

Course Covers 3 Course Covers 3 IssuesIssues

Object Oriented Development Process– e.g USDP

Usage of UML notation– e.g Usecase Model

Object Orientation- basic concepts– e.g encapsulation, inheritance

Page 3: OOSAD-UML_Lec02-1

3

Week -1 : Discussion PointsWeek -1 : Discussion Points

Evolution of object-orientation Abstraction OO approach- Advantages UML- an introduction Objects- basic concepts

Based on Chapter 4 & 5 of B,M&F

Page 4: OOSAD-UML_Lec02-1

8/26/03 4

Aim of Software EngineeringProduce Quality Software

–Less effort (easy development process)–Less cost and time

Quality Software ?–Reliable - Reusable–Robust - Maintainable–Efficient - Userfriendly, etc.

Page 5: OOSAD-UML_Lec02-1

8/26/03 5

Object Oriented ParadigmOO Analysis

OO Design

OO Programming

OO Database

Page 6: OOSAD-UML_Lec02-1

6

Evolution - to OO Evolution - to OO ApproachApproach Early machine- single programmer-

machine code & assembler Next level machines- High level

programming Moderate machines- program groups

– GOTO - structured programming Efficient machines- Structured Design

and Analysis methods

Page 7: OOSAD-UML_Lec02-1

7

Evolution- to Evolution- to OOOO 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

Page 8: OOSAD-UML_Lec02-1

8

AbstractionAbstraction Focus only on essential issues Ignores unnecessary detailE.gsAll areHuman Bones Nerves Heart

Tiger

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?

Page 9: OOSAD-UML_Lec02-1

9

Unified Software Development Unified Software Development ProcessProcess

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

Page 10: OOSAD-UML_Lec02-1

10

USDPUSDP

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

Page 11: OOSAD-UML_Lec02-1

11

Size of square relative to time spent on workflowh

Inception Elaboration Construction TransitionProject Phases 1 2 3 4 5 6 7 8

Iterations within each phase

Requirements

Analysis

Design

Implementation

Test

Workflows

Within each phase activities are grouped into work-flows

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

Within phases there may be more than one iteration

Page 12: OOSAD-UML_Lec02-1

12

Two main OO Two main OO characteristicscharacteristics

Object level Abstraction In Structured Mtds, modular level

abstraction only

Seamless Transition between phases In Structured Mtds, ER, DFD to Structure

Chart, etc.

viewBalancebalanceaccNo module

Page 13: OOSAD-UML_Lec02-1

13

Two main AdvantagesTwo main Advantages

Good Quality software

Easy development process

Page 14: OOSAD-UML_Lec02-1

14

Object level AbstractionObject level Abstraction

Objects in process resembles real-world objects - conceptually similar ideas

Object is a self contained package– manipulated using well-defined

interface (e.g. myAccount.viewbalance( ))

myAccountviewBalance()

Object

Page 15: OOSAD-UML_Lec02-1

15

Seamless TransitionSeamless 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

Page 16: OOSAD-UML_Lec02-1

16

Structured Vs OO approachStructured Vs OO approach

Account

aNo balance

Account

withdraw

amount

messagewithdrawal

amount message

ER DFD with Data Store Structure Chart

:MyAccountwithdraw(X)

MyAccount::

aNo= 101balance=500

balance( )withdraw( )- - -

Objects

OO approachOO approach

StructuredStructured

Page 17: OOSAD-UML_Lec02-1

17

Easy Development Process - Easy Development Process - why?why?

Problem domain is well understood– productivity increased

Good communication between stake holders – reworking reduced

Use of reusable objects– reinventing avoided

Page 18: OOSAD-UML_Lec02-1

18

Easy Development Process - Easy Development Process - why?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

Page 19: OOSAD-UML_Lec02-1

19

Good Quality Software - Good Quality Software - why?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

Page 20: OOSAD-UML_Lec02-1

20

UML have several models -Why UML have several models -Why Model?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

Page 21: OOSAD-UML_Lec02-1

21

ModelModel

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 Use-

case diagram and use-case descriptions A model can evolve

Page 22: OOSAD-UML_Lec02-1

22

UML- an introductionUML- 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)

Page 23: OOSAD-UML_Lec02-1

23

More on UMLMore 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

Page 24: OOSAD-UML_Lec02-1

24

Diagrams in UMLDiagrams in UML UML diagrams are well defined in

the UML specification.– E.g. use case diagram

UML diagrams consist of:– icons– two-dimensional symbols– paths– Strings

There are 9 types of diagrams in UML

Plan Chapter

Produce First Draft

Revise Draft

[satisfied]

[not satisfied]

Add Exercises

Add Referencesto Bibliography

Write Chapter

Activity diagram

Page 25: OOSAD-UML_Lec02-1

25

Activity Activity DiagramDiagram

An Example: Activity

diagram of the tasks involved in producing a book.

Using Swim-lanes

Write Chapter

Review Chapter

Author PrinterTypesetterReviewer

Typeset Book

Correct Proofs

Reset Book

Print Book

[book complete]

[book notcomplete]

Revise Chapter

Page 26: OOSAD-UML_Lec02-1

26

System- 4+1 view in UMLSystem- 4+1 view in UML

Different models present different views of the system, for example:– logical view– process view– implementation view– deployment viewAnd– use case view

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

Page 27: OOSAD-UML_Lec02-1

27

UML- Models and ViewsUML- 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)– Configuration view ( Deployment Diagram)

Page 28: OOSAD-UML_Lec02-1

28

Examples of some UML Examples of some UML ModelsModels

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

Page 29: OOSAD-UML_Lec02-1

29

Iteration on Use Case ModelIteration on Use Case Model

Iteration 1Obvious use cases.Simple use case descriptions.

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

Iteration 3Structured use cases.Structured use case descriptions.Prototypes.

Assign staff to work on

a campaign

Campaign Manager

Add a new advert to

a campaign

Check campaign budget

Find campaign

Accountant

summary Print campaign

invoice

«include»

«extend» «extend»

Print campaign

«include»

«include»

Campaign Management

Assign staff to work on

a campaign

Campaign Manager

Add a new advert to

a campaign

Check campaign budget

Find campaign

Accountant

summary Print campaign

invoice

«include»

«extend» «extend»

Print campaign

«include»

«include»

Campaign Management

Calculate staff bonuses

Accountant

Add a new staff member

Add a new staff grade

Change the rate for a

staff grade

Change the grade for a

staff member

Staff Management

Calculate staff bonuses

Accountant

Add a new staff member

Add a new staff grade

Change the rate for a

staff grade

Change the grade for a

staff member

Staff Management

Calculate staff bonuses

Accountant

Add a new staff member

Add a new staff grade

Change the rate for a

staff grade

Change the grade for a

staff member

Staff Management

Calculate staff bonuses

Accountant

Add a new staff member

Add a new staff grade

Change the rate for a

staff grade

Change the grade for a

staff member

Staff Management

Calculate staff bonuses

Accountant

Add a new staff member

Add a new staff grade

Change the rate for a

staff grade

Change the grade for a

staff member

Staff Management

Assign staff to work on

a campaign

Campaign Manager

Add a new advert to

a campaign

Check campaign budget

Find campaign

Accountant

summary Print campaign

invoice

«include»

«extend» «extend»

Print campaign

«include»

«include»

Campaign Management

Spring Jewellery Campaign 1997Spring Jewellery Campaign 2001Spring Jewellery Campaign 2002Summer Collection 1998

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Yellow Partridge

Spring Jewellery Campaign 1997Spring Jewellery Campaign 2001Spring Jewellery Campaign 2002Summer Collection 1998

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Yellow Partridge

Spring Jewellery Campaign 2002

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Spring Jewellery Campaign 1997Spring Jewellery Campaign 2001Spring Jewellery Campaign 2002Summer Collection 1998

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Yellow Partridge

Spring Jewellery Campaign 1997Spring Jewellery Campaign 2001Spring Jewellery Campaign 2002Summer Collection 1998

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Yellow Partridge

Spring Jewellery Campaign 2002

OK Quit

Campaign:

Campaign Selection

Holborn MotorsLynch PropertiesYellow Partridge Zeta Systems

Client:

Page 30: OOSAD-UML_Lec02-1

30

OBJECTSOBJECTS

Page 31: OOSAD-UML_Lec02-1

31

Objects - basic conceptsObjects - basic concepts

Based on Chapter 4 of Bennett, McRobb and Farmer:

Object Oriented Systems Analysis and Design Using UML, (2nd Edition), McGraw Hill, 2002.

Page 32: OOSAD-UML_Lec02-1

32

Object- Basic ConceptsObject- 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

Page 33: OOSAD-UML_Lec02-1

33

ObjectsObjectsAn 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)

Page 34: OOSAD-UML_Lec02-1

34

ObjectsObjects“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

Page 35: OOSAD-UML_Lec02-1

35

-- -- abstraction of something in a abstraction of something in a domain--domain--

2-Door, Automatic, Red, Honda

Jet, Compression

MechanicPublic

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

CAR- in game SW Vs CAR - in Insurance SW

ID, speed, color, location regNo, model, owner, value

draw( ), changeSpeed( ) getValue( ), getOwner( )

Page 36: OOSAD-UML_Lec02-1

36

ExampleExampleCar is an object

Identity – my car State (current )

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.

My car is a car.It is not a truck

There are many cars. All have some things in common

Page 37: OOSAD-UML_Lec02-1

37

IdentityIdentity 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.

My new red car

Page 38: OOSAD-UML_Lec02-1

38

StateStateonClaim / completed/ noClaim

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

OnReserveOnBind

Page 39: OOSAD-UML_Lec02-1

39

ChangeSpeed(100)

gear=neutralBehaviourBehaviour 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( )OFFCAR

onLoan?

onShelfCOPYComplete this !

Behaviors are implemented as operations.

Page 40: OOSAD-UML_Lec02-1

40

ClassClass

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)

Page 41: OOSAD-UML_Lec02-1

41

Class, and Instance Class, and Instance (Object)(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

Page 42: OOSAD-UML_Lec02-1

42

Class and Class and ObjectsObjects

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 ?)

Page 43: OOSAD-UML_Lec02-1

43

Class and ObjectsClass and Objects - - an implementation point an implementation point of viewof view

Account

aNobalancedayLimit = 200

balance( )withdraw( )- - -

Name of Class

Data Declaration

Methods Definition

SamAcc::Account

aNo = 101balance = 500

Name of Object

Data Values

Class variable

MicAcc::Account

aNo = 105balance = 600

Name of Object

Data Values

instances

SamAcc::aNo=101balance=500

balance(?)

withdraw(X)

Page 44: OOSAD-UML_Lec02-1

44

Information Hiding in real Information Hiding in real ObjectsObjects

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

Page 45: OOSAD-UML_Lec02-1

45

EncapsulationEncapsulation 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 can’t access its data in principle.

Object is only accessible through its interface.

My Account::aNo=101balance=300

balance(?)

withdraw(X)

Account

aNobalancebalance( )withdraw( )- - -

Name of Class

Data(usually hidden)

Methods(usually interface)

-3 advantages ? )easy to use

less coupling

more reliable

Page 46: OOSAD-UML_Lec02-1

46

Message-passingMessage-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.

Page 47: OOSAD-UML_Lec02-1

47

Message-Message-passingpassing

Client object request a service from a 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)

user

Interloan

libraryrequest

service

methods

aNobalance

ATM-UI:: MyAccount::

transfer( ) withdraw( )message method

deposit( )

message

Page 48: OOSAD-UML_Lec02-1

48

Message-passing and Message-passing and EncapsulationEncapsulation

Message from another object requests a service.

Operation called only via valid operation signature.

Data accessed only by object’s own operations.

An object’s data is hidden

(encapsulated).

‘Layers of an onion’ model of an object:

An outer layer of operation signatures…

…gives access to middle layer of operations…

…which can access inner core of data

Page 49: OOSAD-UML_Lec02-1

49

Reusability:Reusability: OO Vs Structured approaches OO Vs Structured approaches

Which is more reusable?

Account

aNo balance

Account

withdraw

amount

messagewithdrawal

amount message

ER DFD with Data Store Structure Chart

MyAccount::aNo=101balance=300

withdraw(X)

Account

aNobalance

balance( )withdraw( )- - -

Class &Object

• Can we separate ER, DFD, and Structure chart together from other parts and use it in other applications?

Page 50: OOSAD-UML_Lec02-1

50

Generalization and Generalization and SpecializationSpecialization

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

Page 51: OOSAD-UML_Lec02-1

51

Specialization Specialization HierarchyHierarchy

monthly paid

Person

Employee Customer Supplier

weekly paid

hourly paid

Driver Cleaner Sales assistant

More general(superclasses)

More specialized(subclasses)

Subclasses are fully Consistent with super classes and add more information

Abstraction

Real-world entities on leaves

Page 52: OOSAD-UML_Lec02-1

52

Super class Vs Sub Super class Vs Sub classclass More general/common bits of description are

abstracted out from specialized classes:

HourlyPaidDriverStartDateStandardRateOvertimeRateLicenceType

PersonNameDate of birthGenderTitle

General (superclass or base class)

Specialized (subclass)

age ( )

Page 53: OOSAD-UML_Lec02-1

53

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

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.A student is a n-times person (wrong)Cannot be instantiated by ‘links’(person is

abstract).

internalextramural

Page 54: OOSAD-UML_Lec02-1

54

Inheritance - Inheritance - an G&S an G&S implementationimplementation 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

Page 55: OOSAD-UML_Lec02-1

55

Inheritance - Inheritance - an examplean example ‘Savings’ class now

have, 4 attributes and3 methods

MySavings.balance( )will give balance.

withdraw( ) will be overridden. Why we need withdraw( ) in

Account class?

Account

aNobalance

balance( )withdraw( )

SavingsdayLmtdaySofarwithdraw( )reset( )

Current

odLmt

withdraw( )

class variables

What are the advantages?

Page 56: OOSAD-UML_Lec02-1

56

G&S (or Inheritance) - G&S (or Inheritance) - AdvantagesAdvantages 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?)

Page 57: OOSAD-UML_Lec02-1

57

Abstract Classes & Abstract Abstract Classes & Abstract MethodsMethods A base class is known as an ABSTARCT

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

Account

aNobalance

balance( )withdraw( )

SavingsdayLmtdaySofarwithdraw( )reset( )

Current

odLmt

withdraw( )

class variables

Page 58: OOSAD-UML_Lec02-1

58

More on More on InheritanceInheritance

Member

Staff Student

Student

Internal Local

Student

mode

PGrads UGradsLocal

type

LocalPGrads

Student

Asian Local

Overlapping?

Complete?

Disjoint?

Discriminator

International

Page 59: OOSAD-UML_Lec02-1

59

Multiple Multiple InheritanceInheritance

A class may be member of more than one hierarchy and it inherits characteristics from both side ancestors.

Student

PGrad UGrad

Staff

Support Academic

PGdAcad

• 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.

What are the complexities?

Page 60: OOSAD-UML_Lec02-1

60

Poly-morph-Poly-morph-ismism

‘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

==>Many-form-==>Many-form-ismism

Pray!Jesus

Siva

BuddahA---

Page 61: OOSAD-UML_Lec02-1

61

Polymorphism - ExamplesPolymorphism - ExamplesCampaign

titlecampaignStartDatecampaignFinishDate

getCampaignAdverts()addNewAdvert()

<<entity>>

Campaign

titlecampaignStartDatecampaignFinishDate

getCampaignAdverts()addNewAdvert()

<<entity>>• Resize Operations

• A request to an object of Account family

::Cheque

Account::ATM interfaceWithdraw()

requestMoney

user

Withdraw() Withdraw()::Savings

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

OR

resize( x)

resize( x)

Page 62: OOSAD-UML_Lec02-1

62

OverloadinOverloadingg

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.

He is noodlesSpoonEating.He is noodlesStickEating.He is riceSpoonEating.He is riceStickEating.

My car is eating petrol

Is it possible in pascal?

Page 63: OOSAD-UML_Lec02-1

63

OverrridingOverrriding Overriding is an act of redefining an

operation of a supperclass differently in its derived class.Account

withdraw( )

Savings

withdraw( )

ChildSavings

withdraw( )

Amount+ soFar < Lmt

amount+daySofar< dayLmt

inherits

overides

no code-skeltonAbstract methodinherits

overides

The method withdraw() will be inheritted from Savings to HouseLoan (this checks ‘daySofar’), but redefinning withdraw() in ChildSa (which instead checks ‘Lmt’) overrides that operation.

• An attribute cannot be overriden

Page 64: OOSAD-UML_Lec02-1

64

Polymorphism is Polymorphism is Run-time polymorphismRun-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( )

Page 65: OOSAD-UML_Lec02-1

65

Which is Which is Polymorphism?Polymorphism?

Class1

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

Class2

method1(paralist1);

Ad-hoc– :Class1.method1(paralist1)– :Class1.method1(paralist2)

Inherited– :Class1.method1(paralist2)– :Class2.method1(paralist2)

Run-time– :Class1.method1(paralist1)– :Class2.method1(paralist1)

::Cheque

Account::ATM interfacewithdraw()

requestMoney

user

withdraw( ) withdraw()::Savings

Same class, different tasks

Different classes, same task

Different classes, different tasks

overload

Override (which method? - not known until run time)

inherit

Page 66: OOSAD-UML_Lec02-1

66

An Abstract Class and an Abstract An Abstract Class and an Abstract MethodMethod

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( )

AccountaccNobalancebalance( )withdraw( )

ChequeODLimit

withdraw( )

Page 67: OOSAD-UML_Lec02-1

67

Overriding, Inheritance, ReusingOverriding, Inheritance, Reusing

public class Savings extends Account{

public Savings(int an, int b){

super (an, b);}

public void withdraw(int amount){

if (balance > amount) balance -= amount;

}}

Savings

withdraw( )

AccountaccNobalancebalance( )withdraw( )

ChequeODLimit

withdraw( )

Page 68: OOSAD-UML_Lec02-1

68

Overriding, Class VariableOverriding, Class Variable

public class Current extends Account{

private static int ODlimit=100;public Current(int an, int b){

super (an, b);}public void withdraw(int amount){

if (balance+ODlimit > amount) balance -=

amount;}

}

Savings

withdraw( )

AccountaccNobalancebalance( )withdraw( )

ChequeODLimit

withdraw( )

Page 69: OOSAD-UML_Lec02-1

69

Run-time and inherited Run-time and inherited polymorphismpolymorphismimport java.io.*;public class withdrawCtrl{ public Account getAccount()throws IOException { int d =2; Account A; if (d==1) A= new Savings(100, 1000); else A= new Current(120,2000); return A; } public void withdraw() throws IOException { Account A; A=getAccount(); int amount =100;

A.withdraw(amount); }}

Savings

withdraw( )

AccountaccNobalancebalance( )withdraw( )

ChequeODLimit

withdraw( )

System.out.println( A.balance() );

Page 70: OOSAD-UML_Lec02-1

70

Run-time Polymorphism and Run-time Polymorphism and ReusabilityReusability

Savings

withdraw( )

AccountaccNobalancebalance( )withdraw( )

ChequeODLimit

withdraw( )

If we want a ‘Child-SavingsAccount’ that impose a limit

(say 10% of the balance)on withdrawal amount,What we need to do?

Page 71: OOSAD-UML_Lec02-1

71

Advantages of Advantages of PolymorphismPolymorphism

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 may be reused.

Page 72: OOSAD-UML_Lec02-1

72

Objects Objects --More IssuesMore 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

Page 73: OOSAD-UML_Lec02-1

73

RelationshipsRelationships(sta(static)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

lendTomUML

giveDetail( )

•Dependency relationship will be discussed later.

Page 74: OOSAD-UML_Lec02-1

74

AssociationAssociation

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

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

business interactions.– bi-directional (direction for name may be shown)– weak coupling between classes – navigational direction may be included later

employee

worksFor

employerTomFarmer

s

Link

employee

worksFor

employer0..1*

0..* personcompany

Association

Link is an instance of an association.

Page 75: OOSAD-UML_Lec02-1

75

MultiplicitMultiplicityy

Role names - may be used with association at both ends or at one of the ends to increase clarity

employee

worksFor

employer0..1

0..* personcompany

person

manages

manager

* 1

EmployeeRole names are specially important for reflexive relationships with multiplicity constraint.

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

Page 76: OOSAD-UML_Lec02-1

76

OtherOtherConstraintsConstraints

placeOn

1 0..* holdbook{ordered}

employee1 *

personcompany

{subset} manager1 *

account* *

Account

Person{exclusive or} account1 *Organiz

a

perOwner

orgOwner

OrderedHolds must be in some order

SubsetManager must be an employee

XORPrevents artificial subclasses

Page 77: OOSAD-UML_Lec02-1

77

Tertiary Tertiary RelationsRelations

CourseStudent

Lecturer

Scheduleroomtime

Student

Lecturer

Course<<ternary>>

Scheduleroomtime

OR

•Where can we keep ‘room’?

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

•Another example?

Page 78: OOSAD-UML_Lec02-1

78

Association class Association class ( usually for m*n ( usually for m*n relationships)relationships)

•If needs some operation or participate in relationships with other objects

•Only used to hold attributes of a relationship

1..* 0..*

dateIncluded

UsedFor

account card

Associationclass

0..* 1..*

grade

student course

Attributed Attributed AssociationAssociation

No Name

Page 79: OOSAD-UML_Lec02-1

79

AggregatioAggregationn

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

•Strong coupling; one end plays more important role. Not independent.

•Holds transitivity and asymmetry propertiesA is-a-part-of B, B is-a-part-of C A is-a-part-of CA 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

Staff Dependants**

Degree**

Page 80: OOSAD-UML_Lec02-1

80

CompositioCompositionn

•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)

Drawing

Line Circle

Invoice

Invoic-LinesThis may be recursive.

Page 81: OOSAD-UML_Lec02-1

81

Visibility (of class Visibility (of class members)members)

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

Account

- nextAno- aNo# balance

+ balance( )+ withdraw( )

Visibility affects the accessibility of a class member

outside its boundary

Package ??

Page 82: OOSAD-UML_Lec02-1

82

VisibilityVisibility

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)

Account

- aNo# balance

+ balance( )+ withdraw( )

MySAcc:Savings

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

- - -

MyCAcc:Current

nextCno = 601aNo = 321balance = 5640ODlimit = 1000

withdraw( )

- - -

balance = balance – amount

setBalance(balance( )-amount)

Page 83: OOSAD-UML_Lec02-1

83

BindingBinding

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?

The process of determining which process to be invoked for a certain message call

Swithdraw()

Cwithdraw()

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

Page 84: OOSAD-UML_Lec02-1

84

Meta-class and Meta-class and Class scope Class scope attributesattributes

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. Meta–class 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 far.

Page 85: OOSAD-UML_Lec02-1

85

PersistencPersistencee

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.