oosad-uml_lec02-1
DESCRIPTION
Object oriented analysisTRANSCRIPT
8/26/03 1
Object Oriented Analysis & Design
Object Oriented Systems Analysis and Design Using UML, McGraw Hill, 2002. By Bennett, McRobb and Farmer
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
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
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.
8/26/03 5
Object Oriented ParadigmOO Analysis
OO Design
OO Programming
OO Database
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
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
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?
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
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
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
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
13
Two main AdvantagesTwo main Advantages
Good Quality software
Easy development process
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
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
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
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
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
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
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
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
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)
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
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
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
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)
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)
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
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:
30
OBJECTSOBJECTS
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.
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
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)
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
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( )
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
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
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
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.
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)
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
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 ?)
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)
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
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
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.
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
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
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?
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
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
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 ( )
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
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
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?
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?)
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
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
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?
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---
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)
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?
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
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( )
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
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( )
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( )
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( )
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() );
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?
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.
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
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.
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.
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
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
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?
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
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**
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.
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 ??
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)
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
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.
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.