47
eMacao eMacao-14 14-03 03 -1 Object Object- Oriented Principles Oriented Principles Robert P. Biuk Robert P. Biuk-Aghai Aghai Department of Computer and Information Science Department of Computer and Information Science Faculty of Science and Technology Faculty of Science and Technology University of Macau University of Macau [email protected] [email protected] eMacao eMacao-14 14-03 03 -2 Overview Overview Why Object Why Object -Orientation? Orientation? The Object Model The Object Model OO vs. Procedure OO vs. Procedure- Oriented Approach Oriented Approach Fundamental OO Concepts Fundamental OO Concepts Examples Examples Conclusions Conclusions

oomd1

Embed Size (px)

Citation preview

Page 1: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 1/46

eMacaoeMacao--1414--0303--11

ObjectObject--Oriented PrinciplesOriented Principles

Robert P. BiukRobert P. Biuk--AghaiAghai

Department of Computer and Information ScienceDepartment of Computer and Information Science

Faculty of Science and TechnologyFaculty of Science and TechnologyUniversity of MacauUniversity of Macau

[email protected]@umac.mo

eMacaoeMacao--1414--0303--22

OverviewOverview

Why ObjectWhy Object--Orientation?Orientation?

The Object ModelThe Object Model

OO vs. ProcedureOO vs. Procedure--Oriented ApproachOriented ApproachFundamental OO ConceptsFundamental OO Concepts

ExamplesExamples

ConclusionsConclusions

Page 2: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 2/46

eMacaoeMacao--1414--0303--33

Why ObjectWhy Object--Orientation?Orientation?

eMacaoeMacao--1414--0303--44

Why ObjectWhy Object--Orientation?Orientation?

TheThe software crisis software crisis 

nn Software is of poor qualitySoftware is of poor quality

nn Software is expensive to produceSoftware is expensive to produce

nn Software complexity is continuously increasingSoftware complexity is continuously increasing

Page 3: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 3/46

eMacaoeMacao--1414--0303--55

Why ObjectWhy Object--Orientation?Orientation? (cont(cont’’d.)d.)

Specific problems:Specific problems:

nn 30% of large software projects are cancelled before30% of large software projects are cancelled beforecompletioncompletion

nn 50% of software projects are over budget by more than50% of software projects are over budget by more than200%200%

nn The majority of completed projects deliver 60% or less ofThe majority of completed projects deliver 60% or less ofprescribed functionalityprescribed functionality

nn Many delivered information systems are underMany delivered information systems are under--usedused

because they donbecause they don’’t meet user needs and/or expectationst meet user needs and/or expectationsnn Legacy systems are a serious and growing bottleneck toLegacy systems are a serious and growing bottleneck to

organizational evolutionorganizational evolution

ObjectObject--orientation: a possible way out of the crisisorientation: a possible way out of the crisis

eMacaoeMacao--1414--0303--66

Key Quality ConcernsKey Quality Concerns

Correctness Correctness nn ““The ability of software products to perform their exactThe ability of software products to perform their exact

tasks, as defined by their specifications.tasks, as defined by their specifications.”” [Mey97][Mey97]

Robustness Robustness nn ““The ability of software systems to react appropriately toThe ability of software systems to react appropriately to

abnormal conditions.abnormal conditions.”” [Mey97][Mey97]

Difficulties:Difficulties:

nn Producing bugProducing bug--free softwarefree software

nn Correcting software bugsCorrecting software bugs

àà Common problem: softwareCommon problem: software reliability reliability 

Page 4: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 4/46

eMacaoeMacao--1414--0303--77

Key Quality ConcernsKey Quality Concerns (cont(cont’’d.)d.)

Reusability Reusability 

nn ““The ability of software elements to serve for theThe ability of software elements to serve for theconstruction of many different applications.construction of many different applications.”” [Mey97][Mey97]

Extendibility Extendibility nn ““The ease of adapting software products to changes ofThe ease of adapting software products to changes of

specification.specification.”” [Mey97][Mey97]

Difficulties:Difficulties:nn

Changing software is hardChanging software is hardnn Hard to apply software outside its original intended useHard to apply software outside its original intended use

àà Common problem: softwareCommon problem: software modularity modularity 

eMacaoeMacao--1414--0303--88

Other Quality ConcernsOther Quality Concerns

CompatibilityCompatibilitynn The ease of combining software elements with others.The ease of combining software elements with others.

PortabilityPortabilitynn The ease of transferring software products to variousThe ease of transferring software products to various

hardware and software environmentshardware and software environments

Ease of useEase of use

nn The ease with which people of different backgrounds canThe ease with which people of different backgrounds canlearn to use software productslearn to use software products

EfficiencyEfficiency

nn The ability of a software system to place as few demandsThe ability of a software system to place as few demandsas possible on hardware resourcesas possible on hardware resources

Timeliness, economy and functionalityTimeliness, economy and functionality

Page 5: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 5/46

eMacaoeMacao--1414--0303--99

ObjectObject--OrientationOrientation

AA way of thinking way of thinking about a problemabout a problem

nn Regard the world as consisting of interacting objectsRegard the world as consisting of interacting objects

nn Aim to understand objects, their properties, operations,Aim to understand objects, their properties, operations,and interactions with other objectsand interactions with other objects

A way ofA way of solving problems solving problems 

nn Build systems consisting of representations of objectsBuild systems consisting of representations of objects

nn Objects interact with each otherObjects interact with each other

eMacaoeMacao--1414--0303--1010

Objects ExampleObjects Example

Chair

OHP

Data

Projector

Loud-

speaker

Microphone

PC

Page 6: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 6/46

eMacaoeMacao--1414--0303--1111

Strengths of Object OrientationStrengths of Object Orientation

Describing large, complex systems as interactingDescribing large, complex systems as interactingobjects makeobjects makess themthem easier to understand easier to understand thanthanotherwiseotherwise

TheThe behavio behavio u u rs rs of real world objects tend to beof real world objects tend to bestable stable over timeover time

The differentThe different kinds kinds of real world objects tend to beof real world objects tend to bestable stable (i.e., new kinds appear slowly; old kinds(i.e., new kinds appear slowly; old kinds

disappear slowly)disappear slowly)Changes Changes tend to betend to be localized localized to a few objectsto a few objects

eMacaoeMacao--1414--0303--1212

Strengths of Object OrientationStrengths of Object Orientation (cont(cont’’d)d)

A single paradigmA single paradigmnn Single language used by users, analysts, designers,Single language used by users, analysts, designers,

implementersimplementers

Facilitates architectural and code reuseFacilitates architectural and code reuse

Models more closely reflect the real worldModels more closely reflect the real worldnn More accurately describe corporate data and processesMore accurately describe corporate data and processes

nn Decomposed based on natural partitioningDecomposed based on natural partitioning

nn Easier to understand and maintainEasier to understand and maintain

StabilityStability

nn A small change in requirements does not mean massiveA small change in requirements does not mean massive

changes in the system under developmentchanges in the system under development

Page 7: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 7/46

eMacaoeMacao--1414--0303--1313

Strengths of Object OrientationStrengths of Object Orientation (cont(cont’’d)d)

Overall benefits of OO:Overall benefits of OO:

Proper use of OO methodsProper use of OO methods enhances key software enhances key software quality factors quality factors of a system and its constituentof a system and its constituentcomponentscomponents

eMacaoeMacao--1414--0303--1414

OOA, OOD, OOPOOA, OOD, OOP

Application of objectApplication of object--orientation throughout theorientation throughout thesoftware lifesoftware life--cycle:cycle:

Evaluation

Analysis

Design

Coding

Testing

Maintenance

Page 8: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 8/46

eMacaoeMacao--1414--0303--1515

OOA: ObjectOOA: Object--Oriented AnalysisOriented Analysis

Definition:Definition:

nn Object Object - - oriented analysis is a method of analysis that oriented analysis is a method of analysis that examines requirements from the perspective of the examines requirements from the perspective of the classes and objects found in the vocabulary of the classes and objects found in the vocabulary of the problem domain.problem domain. [Boo94][Boo94]

Supported by OO modeling methods:Supported by OO modeling methods:nn UMLUML

nn OMTOMT

nn etc.etc.

eMacaoeMacao--1414--0303--1616

OOD: ObjectOOD: Object--Oriented DesignOriented Design

Definition:Definition:nn Object Object - - oriented design is a method of design oriented design is a method of design 

encompassing the process of object encompassing the process of object - - oriented oriented 

decomposition and a notation for depicting both logical decomposition and a notation for depicting both logical and physical as well as static and dynamic models of the and physical as well as static and dynamic models of the 

system under design.system under design. [Boo94][Boo94]

Supported by OO design methods:Supported by OO design methods:nn UMLUML

nn OMTOMT

nn etc.etc.

Page 9: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 9/46

eMacaoeMacao--1414--0303--1717

OOP: ObjectOOP: Object--Oriented ProgrammingOriented Programming

Definition:Definition:

nn Object Object - - oriented programming is a method of oriented programming is a method of implementation in which programs are organized as implementation in which programs are organized as cooperative collections of objects, each of which cooperative collections of objects, each of which represents an instance of some class, and whose represents an instance of some class, and whose 

classes are all members of a hierarchy of classes united classes are all members of a hierarchy of classes united via inheritance relationships via inheritance relationships . [Boo94]. [Boo94]

Supported by OO programming languages:Supported by OO programming languages:

nn C++C++nn JavaJava

nn SmalltalkSmalltalk

nn EiffelEiffel

nn etc.etc.

eMacaoeMacao--1414--0303--1818

The Object ModelThe Object Model

Page 10: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 10/46

eMacaoeMacao--1414--0303--1919

The Object ModelThe Object Model

AA ““sound engineering foundationsound engineering foundation”” [Boo94][Boo94]

A different way of thinking about softwareA different way of thinking about software(i.e. as a set of interacting objects)(i.e. as a set of interacting objects)

Four basic principles:Four basic principles:1.1. AbstractionAbstraction

2.2. EncapsulationEncapsulation

3.3. ModularityModularity

4.4. HierarchyHierarchy

Object Orientation

      E     n     c     a     p     s     u      l     a      t      i     o     n

      A      b     s      t     r     a     c      t      i     o     n

      H      i     e     r     a     r     c      h     y

      M     o      d     u      l     a     r      i      t     y

eMacaoeMacao--1414--0303--2020

AbstractionAbstraction

Definition:Definition:nn An abstraction denotes the essential characteristics of an An abstraction denotes the essential characteristics of an 

object that distinguish it from all other kinds of objects object that distinguish it from all other kinds of objects 

and thus provide crisply defined conceptual boundaries,and thus provide crisply defined conceptual boundaries,relative to the perspective of the viewer.relative to the perspective of the viewer. [Boo94][Boo94]

Key concepts:Key concepts:

nn Concentrating only onConcentrating only on essential characteristics essential characteristics àà Allows complexity to be more easily managedAllows complexity to be more easily managed

nn Abstraction isAbstraction is relative to the perspective of the viewer relative to the perspective of the viewer 

àà Many different views of the same object are possibleMany different views of the same object are possible

Page 11: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 11/46

eMacaoeMacao--1414--0303--2121

Different Viewpoints of an ObjectDifferent Viewpoints of an Object

 S  o ur  c  e: B  o o 9 4 

eMacaoeMacao--1414--0303--2222

Examples of AbstractionExamples of Abstraction

Customer

Employee

Product

Page 12: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 12/46

eMacaoeMacao--1414--0303--2323

EncapsulationEncapsulation

Definition:Definition:

nn Encapsulation is the process of compartmentalizing the Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure elements of an abstraction that constitute its structure and behaviour; encapsulation serves to separate the and behaviour; encapsulation serves to separate the contractual interface of an abstraction and its contractual interface of an abstraction and its 

implementation.implementation. [Boo94][Boo94]

Key concepts:Key concepts:

nn Packaging structure and behaviour together in one unitPackaging structure and behaviour together in one unit

àà Makes objects more independentMakes objects more independent

nn Objects exhibit anObjects exhibit an interface interface through which others canthrough which others caninteract with itinteract with itàà Hides complexity from an objectHides complexity from an object’’s clientss clients

eMacaoeMacao--1414--0303--2424

EncapsulationEncapsulation (cont(cont’’d.)d.)

Encapsulation separates the implementation of anEncapsulation separates the implementation of anobjectobject’’s behaviour from its public interfaces behaviour from its public interface

It is calledIt is called ““information hidinginformation hiding””, it allows an object, it allows an object’’ssbehaviour to be used without knowing itsbehaviour to be used without knowing itsimplementation (implementation (““black boxblack box””))

Offers two kinds of security:Offers two kinds of security:nn Protects objectProtects object’’s internal state from being changed bys internal state from being changed by

outside usersoutside users

nn Changes can be done to the behaviour implementationChanges can be done to the behaviour implementationwithout affecting other objectswithout affecting other objects

Page 13: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 13/46

eMacaoeMacao--1414--0303--2525

Encapsulation: Hiding Object DetailsEncapsulation: Hiding Object Details

 S  o ur  c  e: B  o o 9 4 

eMacaoeMacao--1414--0303--2626

Example of EncapsulationExample of Encapsulation

Hide implementation from clientsHide implementation from clientsnn Clients depend only on the interface,Clients depend only on the interface,

not the implementationnot the implementation

Page 14: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 14/46

eMacaoeMacao--1414--0303--2727

ModularityModularity

Definition:Definition:

nn Modularity is the property of a system that has been Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled decomposed into a set of cohesive and loosely coupled modules.modules. [Boo94][Boo94]

Module: a collection of related classes of objectsModule: a collection of related classes of objects

Key concepts:Key concepts:nn Modules areModules are cohesive cohesive (performing a single type of tasks)(performing a single type of tasks)àà Makes modules more reusableMakes modules more reusable

nn Modules areModules are loosely coupled loosely coupled (highly independent)(highly independent)àà Makes modules more robust and maintainableMakes modules more robust and maintainable

eMacaoeMacao--1414--0303--2828

ModularityModularity (cont(cont’’d.)d.)

Modularity can be defined as the process ofModularity can be defined as the process ofbreaking up of a complex system into small, selfbreaking up of a complex system into small, self --

contained pieces that can be managed easilycontained pieces that can be managed easily

Packages and subsystems support the definition ofPackages and subsystems support the definition ofthe modularitythe modularity

Page 15: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 15/46

eMacaoeMacao--1414--0303--2929

Modularity: Separation into PiecesModularity: Separation into Pieces

 S  o ur  c  e: B  o o 9 4 

eMacaoeMacao--1414--0303--3030

Example of ModularityExample of Modularity

The breaking up of something complex intoThe breaking up of something complex intomanageable piecesmanageable pieces

Order ProcessingSystem

Billing

Order

Entry

OrderFulfillment

Page 16: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 16/46

eMacaoeMacao--1414--0303--3131

HierarchyHierarchy

Definition:Definition:

nn Hierarchy is a ranking or ordering of abstractions.Hierarchy is a ranking or ordering of abstractions.[Boo94][Boo94]

Types of hierarchies:Types of hierarchies:

nn ClassClass

nn AggregationAggregation

nn ContainmentContainmentnn InheritanceInheritance

nn PartitionPartition

nn SpecializationSpecialization

eMacaoeMacao--1414--0303--3232

Hierarchy of AbstractionsHierarchy of Abstractions

Source: Boo94

Page 17: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 17/46

eMacaoeMacao--1414--0303--3333

Example of HierarchyExample of Hierarchy

Decreasingabstraction

Increasingabstraction

Asset

RealEstate

Savings

BankAccount

Checking Stock

Security

Bond

Classes at the same level of the hierarchy should be at the same level of abstraction 

Levels of abstractionLevels of abstraction

eMacaoeMacao--1414--0303--3434

ObjectObject--Oriented vs.Oriented vs.

ProcedureProcedure

--OrientedOriented

ApproachApproach

Page 18: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 18/46

eMacaoeMacao--1414--0303--3535

What is ProcedureWhat is Procedure--OrientedOriented

Programming?Programming?Emphasis is onEmphasis is on doing things doing things (algorithms)(algorithms)

Large programs are divided into smaller programsLarge programs are divided into smaller programs(functions)(functions)

Most of the functions share global dataMost of the functions share global data

Data move openly around the system from functionData move openly around the system from functionto functionto function

Functions transform data from one form to anotherFunctions transform data from one form to another

EmploysEmploys top top - - down down approach in program designapproach in program design

eMacaoeMacao--1414--0303--3636

Relationship of Data & Functions inRelationship of Data & Functions in

Procedural ProgrammingProcedural Programming

Global Data Global Data

Function 1

Local Data

Function 2

Local Data

Function 1

Local Data

Page 19: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 19/46

eMacaoeMacao--1414--0303--3737

What is Object OrientedWhat is Object Oriented

Programming?Programming?Emphasis is onEmphasis is on data data rather than procedurerather than procedure

Programs are divided intoPrograms are divided into objects objects (abstracted into(abstracted intoclasses classes ))

Data isData is encapsulated encapsulated in the objectsin the objects

Objects communicate with each other throughObjects communicate with each other throughfunctions (calledfunctions (called methods methods ))

FollowsFollows bottom bottom - - up up approach in program designapproach in program design

eMacaoeMacao--1414--0303--3838

Organization of Data & Functions inOrganization of Data & Functions in

ObjectObject--Oriented ProgrammingOriented Programming

Data

Functions

Object A

Data

Functions

Object B

Data

Functions

Object C

Page 20: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 20/46

eMacaoeMacao--1414--0303--3939

Fundamental OO ConceptsFundamental OO Concepts

eMacaoeMacao--1414--0303--4040

Basic Concepts of Object OrientationBasic Concepts of Object Orientation

ObjectObject

ClassClass

AttributeAttributeOperationOperation

StateState

BehaviourBehaviour

IdentityIdentity

RelationshipsRelationships

PolymorphismPolymorphism

Page 21: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 21/46

eMacaoeMacao--1414--0303--4141

ObjectObject

An object represents anAn object represents an entity entity 

Objects can be:Objects can be:nn Physical Physical oror conceptual conceptual 

nn Tangible Tangible oror intangible intangible 

Objects areObjects are concrete concrete 

Examples of objects:Examples of objects:nn A buildingA building

nn An employeeAn employee

nn A formA form

eMacaoeMacao--1414--0303--4242

ClassClass

A class represents aA class represents a type type of objectof object

A class is a definition of an objectA class is a definition of an object

nn It definesIt defines object structure and behavioobject structure and behaviouurr

A class isA class is aa template (ortemplate (or ““blueprintblueprint””) for producing) for producingobjects of a certain typeobjects of a certain type

Every object is anEvery object is an instance instance of a classof a class

Examples of classes:Examples of classes:nn BuildingBuilding

nn EmployeeEmployee

nn FormForm

Page 22: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 22/46

Page 23: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 23/46

eMacaoeMacao--1414--0303--4545

Example: AttributesExample: Attributes

public class Employee {public class Employee {

protected int employeeNo;protected int employeeNo;

protected String surName;protected String surName;

protected String givenName;protected String givenName;

protected String jobTitle;protected String jobTitle;

protected int salary;protected int salary;

}}

Attributes

eMacaoeMacao--1414--0303--4646

Operation (Method)Operation (Method)

An operation is the implementation of a service that An operation is the implementation of a service that can be requested from any object of the class to can be requested from any object of the class to 

affect behavio affect behavio u u r r .. [[Boo99Boo99]]

An operation can be:An operation can be:nn Question (does not change the value of the object)Question (does not change the value of the object)

nn Command (may change the value of the object)Command (may change the value of the object)

Page 24: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 24/46

eMacaoeMacao--1414--0303--4747

Example: OperationsExample: Operations

public class Employee {public class Employee {

protected int employeeNo;protected int employeeNo;

protected String surName;protected String surName;

protected String givenName;protected String givenName;

protected String jobTitle;protected String jobTitle;

protected int salary;protected int salary;

public void assignWork(Task t) {}public void assignWork(Task t) {}

public void doWork() {}public void doWork() {}

public void submitResult(Result r) {}public void submitResult(Result r) {}

}}

Operations

eMacaoeMacao--1414--0303--4848

Object DefinitionObject Definition

Definition:Definition:nn An object has state, behaviour, and identity; the structure An object has state, behaviour, and identity; the structure 

and behaviour are defined in their common class; the and behaviour are defined in their common class; the 

terms terms instanceinstance and and objectobject are interchangeable.are interchangeable. [Boo94][Boo94]

Example object:Example object:

nn The employeeThe employee Chan Tai Man Chan Tai Man 

Page 25: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 25/46

eMacaoeMacao--1414--0303--4949

ObjectObject StateState

Definition:Definition:

nn The The state state of an object encompasses all of the (usually of an object encompasses all of the (usually static) properties of the object plus the current (usually static) properties of the object plus the current (usually dynamic) values of each of these properties.dynamic) values of each of these properties. [Boo94][Boo94]

Properties of an object areProperties of an object are fixed fixed (static)(static)

PropertyProperty values values of an objectof an object change change (dynamic)(dynamic)

eMacaoeMacao--1414--0303--5050

Example: ObjectExample: Object StateState

Example object state for employeeExample object state for employee Chan Tai Man Chan Tai Man ::nn employeeNo: 1234employeeNo: 1234

nn surName: "Chan"surName: "Chan"

nn givenName: "Tai Man"givenName: "Tai Man"

nn jobTitle: "Tecnico 1a Classe"jobTitle: "Tecnico 1a Classe"

nn salary: 400salary: 400

Page 26: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 26/46

eMacaoeMacao--1414--0303--5151

BehaviourBehaviour

Definition:Definition:

nn Behaviour Behaviour is how an object acts and reacts, in terms of is how an object acts and reacts, in terms of its state changes and message passing its state changes and message passing . [Boo94]. [Boo94]

Example behaviours forExample behaviours foremployeeemployee Chan Tai Man Chan Tai Man ::

nn Updating value ofUpdating value ofpropertyproperty salarysalary

nn Assigning workAssigning work(invoking method(invoking methodassignWork()assignWork()

in the correspondingin the correspondingobject)object)

eMacaoeMacao--1414--0303--5252

Example: BehaviourExample: Behaviour

Example of behaviour: object state change;Example of behaviour: object state change;salary of employeesalary of employee Chan Tai Man Chan Tai Man is increasedis increased

change of property value

An action that updates any of the object’s property values causes a change of the object’s state 

Page 27: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 27/46

eMacaoeMacao--1414--0303--5353

IdentityIdentity

Definition:Definition:

nn Identity Identity  is that property of an object which distinguishes is that property of an object which distinguishes it from all other objects.it from all other objects. [Boo94][Boo94]

Distinct objects remain distinct even when all theirDistinct objects remain distinct even when all theirproperty values are identicalproperty values are identical

Every object has a uniqueEvery object has a unique object identifier object identifier 

Example: twoExample: two Chan Tai Man Chan Tai Man s (in Macau, Portugal)s (in Macau, Portugal)

oid = 2oid = 1

eMacaoeMacao--1414--0303--5454

Modeling ClassesModeling Classes

Modeling more classes of the domain:Modeling more classes of the domain:

Page 28: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 28/46

eMacaoeMacao--1414--0303--5555

Class RelationshipsClass Relationships

Modeled classes can be related in multiple ways:Modeled classes can be related in multiple ways:

nn AssociationAssociation

nn InheritanceInheritance

nn AggregationAggregation

nn UsingUsing

nn InstantiationInstantiation

nn MetaclassMetaclass

The most important and common types ofThe most important and common types ofrelationships:relationships:nn Association, inheritanceAssociation, inheritance

eMacaoeMacao--1414--0303--5656

AssociationAssociation

Association:Association:nn A relationship denoting a semantic connection between A relationship denoting a semantic connection between 

two classes.two classes. [Boo94][Boo94]

Associations may have differentAssociations may have different cardinality cardinality (multiplicity)(multiplicity)nn One One - - to to - - one one : one instance of the first class associated: one instance of the first class associated

with one instance of the second classwith one instance of the second class

nn One One - - to to - - many many : one instance of the first class associated: one instance of the first class associatedwith many instances of the second classwith many instances of the second class

nn ManyMany--toto--many: many instances of the first classmany: many instances of the first classassociated with many instances of the second classassociated with many instances of the second class

Associations are usuallyAssociations are usually bidirectional bidirectional (association(association

applies both ways)applies both ways)

Page 29: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 29/46

eMacaoeMacao--1414--0303--5757

Association ExampleAssociation Example

Example associations:Example associations:

nn Employee isEmployee is head of head of agency / agency isagency / agency is headed by headed by employee (1:1)employee (1:1)

nn EmployeeEmployee works for works for agency / agencyagency / agency provides work provides work forforemployee (1:N)employee (1:N)

eMacaoeMacao--1414--0303--5858

Association Example 2Association Example 2

SelfSelf--association:association:nn Agency is associated to agency (parent agency)Agency is associated to agency (parent agency)

(0(0……1 : 01 : 0……N)N)

GabineteGabinete

DirecDirecççãoão

DepartamentoDepartamento

DivisãoDivisão

SecSecççãoão

Page 30: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 30/46

eMacaoeMacao--1414--0303--5959

InheritanceInheritance

Inheritance:Inheritance:nn A relationship among classes, wherein one class shares A relationship among classes, wherein one class shares 

the structure or behaviour defined in one or more other the structure or behaviour defined in one or more other classes.classes. [Boo94][Boo94]

AA subclass subclass inherits attributes and operations frominherits attributes and operations fromitsits superclass superclass 

Inheritance represents theInheritance represents the is is - - a a relationship:relationship:nn The subclassThe subclass is ais a specialization specialization of the superclassof the superclass

nn The superclassThe superclass is ais a generalization generalization of the subclassof the subclassInheritance is aInheritance is a key concept key concept of objectof object--orientationorientation

Class modeling seeks to identify inheritanceClass modeling seeks to identify inheritancerelationships between classesrelationships between classes

eMacaoeMacao--1414--0303--6060

Inheritance ExampleInheritance Example

Multiple classes with common attributes:Multiple classes with common attributes:nn surNamesurName

nn givenNamegivenName

àà identify aidentify a common superclass common superclass 

Page 31: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 31/46

eMacaoeMacao--1414--0303--6161

Inheritance ExampleInheritance Example (cont(cont’’d.)d.)

Added common superclassAdded common superclass Person Person 

Attributes surName, givenName moved toAttributes surName, givenName moved to Person Person ,,inherited by its subclassesinherited by its subclasses

Attributes of Employee: 

• employeeNo• jobTitle

• salary• agency

+ inherited: • surName• givenName

eMacaoeMacao--1414--0303--6262

Inheritance ExampleInheritance Example (cont(cont’’d.)d.)

public abstract class Person {public abstract class Person {

protected String surName;protected String surName;

protected String givenName;protected String givenName;

}}

public class Employeepublic class Employee extends Personextends Person {{

protected int employeeNo;protected int employeeNo;

protected String jobTitle;protected String jobTitle;

protected int salary;protected int salary;

protected Agency agency;protected Agency agency;

}}

Page 32: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 32/46

eMacaoeMacao--1414--0303--6363

Abstract / Concrete ClassesAbstract / Concrete Classes

A class may beA class may be abstract abstract oror concrete concrete 

Definitions ofDefinitions of abstract class abstract class ::nn A class that cannot be directly instantiated.A class that cannot be directly instantiated. [BRJ99][BRJ99]

nn An abstract class is written with the expectation that its An abstract class is written with the expectation that its concrete subclasses will add to its structure and concrete subclasses will add to its structure and behaviour.behaviour. [Boo94][Boo94]

Definitions ofDefinitions of concrete class concrete class ::nn

A class that can be directly instantiated.A class that can be directly instantiated. [BRJ99][BRJ99]nn A class whose implementation is complete and thus may A class whose implementation is complete and thus may 

have instances.have instances. [Boo94][Boo94]

eMacaoeMacao--1414--0303--6464

Abstract / Concrete Classes ExampleAbstract / Concrete Classes Example

Abstract class:Abstract class: Person Person nn No objects of this class can be createdNo objects of this class can be created

Concrete classes:Concrete classes: Employee Employee ,, Citizen Citizen ,, Visitor Visitor nn Possible to create objects of these classesPossible to create objects of these classes

Page 33: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 33/46

eMacaoeMacao--1414--0303--6565

Abstract / Concrete Classes InheritanceAbstract / Concrete Classes InheritanceExample .Example .

A  b  s  t  r  a

 c  t   c l   a s  s 

 O b  j   e c  t   s 

Concrete classes

eMacaoeMacao--1414--0303--6666

PolymorphismPolymorphism

Polymorphism is the ability to hide manyPolymorphism is the ability to hide manyimplementations behind the same interfaceimplementations behind the same interface

Interface Interface is the outside view of a class, consistingis the outside view of a class, consisting

of its public attributes and operations.of its public attributes and operations.

Example:Example:

nn All employees can apply for leaveAll employees can apply for leave

nn The process of leave application is implementedThe process of leave application is implemented

differently for different kinds of employees (e.g. agencydifferently for different kinds of employees (e.g. agency

heads vs. ordinary employees)heads vs. ordinary employees)

Page 34: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 34/46

eMacaoeMacao--1414--0303--6767

InterfacesInterfaces

Definition:Definition:

nn An interface is a collection of operations that are used to An interface is a collection of operations that are used to specify a service of a class or a component specify a service of a class or a component .. [[BBRJ9RJ999]]

An interface is aAn interface is a contract contract of related services and aof related services and aset of conditions that must be true for the contractset of conditions that must be true for the contractto be faithfully executedto be faithfully executed

Interfaces formalize polymorphism, they allow us toInterfaces formalize polymorphism, they allow us todefine polymorphism in a declarative way unrelateddefine polymorphism in a declarative way unrelatedto implementationto implementation

eMacaoeMacao--1414--0303--6868

ExamplesExamples

Page 35: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 35/46

eMacaoeMacao--1414--0303--6969

Example 1: ObjectsExample 1: Objects

Geometric shapes:Geometric shapes:

nn Many different shapes, but some commonalities (area,Many different shapes, but some commonalities (area,circumference, width, height, centre, etc.)circumference, width, height, centre, etc.)

eMacaoeMacao--1414--0303--7070

Example 1: ClassesExample 1: Classes

Define different classes for different kinds of objectsDefine different classes for different kinds of objects

Ellipse

Circle

Triangle Pentagon Hexagon Octagon

Parallelogram Trapezoid Rectangle Square

Page 36: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 36/46

eMacaoeMacao--1414--0303--7171

Example 1: Class HierarchyExample 1: Class Hierarchy

Shape

Polygon Ellipse

CircleQuadrilateralTriangle Pentagon Hexagon Octagon

Parallelogram Trapezoid

Rectangle

Square

Organize different classes as a hierarchyOrganize different classes as a hierarchy

eMacaoeMacao--1414--0303--7272

Example 1: ClassExample 1: Class

HierarchyHierarchy (cont(cont’’d.)d.)

Put common attributesPut common attributesand operations inand operations in

superclassessuperclasses

Put specializations ofPut specializations ofattributes andattributes andoperations inoperations in

subclassessubclassesnn Subclasses inherit fromSubclasses inherit from

superclassessuperclasses

Page 37: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 37/46

eMacaoeMacao--1414--0303--7373

Example 1: PolymorphismExample 1: Polymorphism

Different implementations of getArea() method:Different implementations of getArea() method:

nn Circle (radiusCircle (radius r r ):): pp ××r r 22

nn Rectangle (vertexesRectangle (vertexes a a ,, b b ,, c c ,, d d ):): a a ××b b 

nn Square (vertexesSquare (vertexes a a ,, b b ,, c c ,, d d ):): a a 22

Different implementations of getCircumference()Different implementations of getCircumference()method:method:

nn Circle (radiusCircle (radius r r ): 2): 2××pp ××r r nn Rectangle (vertexesRectangle (vertexes a a ,, b b ,, c c ,, d d ): 2): 2××(( a a ++ b b ))

nn Square (vertexesSquare (vertexes a a ,, b b ,, c c ,, d d ): 4): 4××a a 

eMacaoeMacao--1414--0303--7474

Example 1: Abstract Class ShapeExample 1: Abstract Class Shape

public abstract class Shapepublic abstract class Shape

{{

public abstract double getArea();public abstract double getArea();

public abstract double getCircumference();public abstract double getCircumference();

}}

Page 38: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 38/46

eMacaoeMacao--1414--0303--7575

Example 1: Class CircleExample 1: Class Circle

public class Circle extends Shapepublic class Circle extends Shape

{{

protected double radius;protected double radius;

public Circle(double radius)public Circle(double radius)

{ this.radius = radius; }{ this.radius = radius; }

public double getArea()public double getArea()

{ return radius * radius * Math.PI; }{ return radius * radius * Math.PI; }

public double getCircumference()public double getCircumference()

{ return radius * 2 * Math.PI; }{ return radius * 2 * Math.PI; }

}}

eMacaoeMacao--1414--0303--7676

Example 1: Class RectangleExample 1: Class Rectangle

public class Rectangle extends Shapepublic class Rectangle extends Shape

{{

protected double width;protected double width;

protected double height;protected double height;

public Rectangle(double width, double height)public Rectangle(double width, double height)

{ this.width = width; this.height = height; }{ this.width = width; this.height = height; }

public double getArea()public double getArea()

{ return width * height; }{ return width * height; }

public double getCircumference()public double getCircumference()

{ return 2 * (width + height); }{ return 2 * (width + height); }

}}

Page 39: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 39/46

eMacaoeMacao--1414--0303--7777

Example 1: Class SquareExample 1: Class Square

public class Square extends Rectanglepublic class Square extends Rectangle

{{

protected double width;protected double width;

protected double height;protected double height;

public Square(double vertex)public Square(double vertex)

{ super(vertex, vertex); }{ super(vertex, vertex); }

public double getArea()public double getArea()

{ return width * height; }{ return width * height; }

public double getCircumference()public double getCircumference()

{ return 4 * width; }{ return 4 * width; }

}}

eMacaoeMacao--1414--0303--7878

Example 1: DiscussionExample 1: Discussion

Design maximizes use of inheritance & polymorphismDesign maximizes use of inheritance & polymorphism

Properties / operations are placed in classes asProperties / operations are placed in classes ashigh up in the class hierarchy as possiblehigh up in the class hierarchy as possible

Subclasses:Subclasses:

nn inherit properties / operationsinherit properties / operations

nn override properties / operationsoverride properties / operations

nn add new properties / operationsadd new properties / operations

Common interface allows different classes to beCommon interface allows different classes to beused interchangeablyused interchangeably

Different implementations through polymorphismDifferent implementations through polymorphism

Page 40: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 40/46

eMacaoeMacao--1414--0303--7979

Example 2: ObjectsExample 2: Objects

A citizen registers a complaint against aA citizen registers a complaint against agovernment agencygovernment agency

Objects (highly simplified view):Objects (highly simplified view):nn CitizenCitizen Lei Wai Keong Lei Wai Keong 

nn ComplaintComplaint

nn AgencyAgency DSSD DSSD 

nn Complaint HandlerComplaint Handler Chan Tai Man Chan Tai Man 

Agency

DSSD

Complaint

Citizen

Lei Wai Keong

Complaint Handler

Chan Tai Man

Complaint

eMacaoeMacao--1414--0303--8080

Example 2: ClassesExample 2: Classes

Page 41: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 41/46

eMacaoeMacao--1414--0303--8181

Example 2: ClassesExample 2: Classes (cont(cont’’d.)d.)

ClassClass Agency Agency ::

nn Provide operationProvide operation postComplaint postComplaint () to citizens() to citizens

nn Queues complaints with the responsibleQueues complaints with the responsibleComplaintHandler ComplaintHandler 

ClassClass ComplaintHandler ComplaintHandler ::

nn Processes complaintsProcesses complaints

nn May forward complaints to other agenciesMay forward complaints to other agencies

ClassClass Complaint Complaint ::nn AllowsAllows Person Person to post complaint (citizen, visitor,to post complaint (citizen, visitor,

employee, etc.)employee, etc.)

eMacaoeMacao--1414--0303--8282

Example 2: ObjectsExample 2: Objects

Page 42: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 42/46

eMacaoeMacao--1414--0303--8383

Example 2: Class ComplaintExample 2: Class Complaint

public class Complaintpublic class Complaint

{{

protected Person complainant;protected Person complainant;

protected Agency complainee;protected Agency complainee;

protected String subject;protected String subject;

protected String description;protected String description;

protected DateTime complaintDateTime;protected DateTime complaintDateTime;

}}

eMacaoeMacao--1414--0303--8484

Example 2: Class AgencyExample 2: Class Agency

public class Agencypublic class Agency

{{

protected String name;protected String name;

protected String address;protected String address;

protected Employee head;protected Employee head;

protected Agency parentAgency;protected Agency parentAgency;

public void postComplaint(Complaint c) {}public void postComplaint(Complaint c) {}

}}

Page 43: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 43/46

eMacaoeMacao--1414--0303--8585

Example 2: Class ComplaintHandlerExample 2: Class ComplaintHandler

public class ComplaintHandler extends Employee {public class ComplaintHandler extends Employee {

protected Queue q;protected Queue q;

public void queueComplaint(Complaint c) {}public void queueComplaint(Complaint c) {}

public void processNextComplaint() {}public void processNextComplaint() {}

public void forwardComplaint(Agency a) {}public void forwardComplaint(Agency a) {}

}}

eMacaoeMacao--1414--0303--8686

Example 2: Interaction between ClassesExample 2: Interaction between Classes

Note : Diagram shows the case when the complaintneeds to be forwarded to another agency

Page 44: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 44/46

eMacaoeMacao--1414--0303--8787

Example 2: DiscussionExample 2: Discussion

Models areModels are generic generic 

nn Independent of any particular agencyIndependent of any particular agency

nn Basis for extension to specific requirementsBasis for extension to specific requirements

Classes areClasses are loosely loosely - - coupled coupled 

nn Can be reused in other applicationsCan be reused in other applicationsàà add other properties / operationsadd other properties / operations

Classes interact throughClasses interact through well well - - defined interfaces defined interfaces nn If necessary, classes can modify their implementationsIf necessary, classes can modify their implementations

(within the scope of specified interfaces) without affecting(within the scope of specified interfaces) without affectingother classesother classes

eMacaoeMacao--1414--0303--8888

ConclusionsConclusions

Page 45: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 45/46

eMacaoeMacao--1414--0303--8989

Virtues of ObjectVirtues of Object--OOrientrientationation

Encapsulation &Encapsulation & data abstractiondata abstraction

nn Easier to modularize code, for better development andEasier to modularize code, for better development anddebuggingdebugging

nn Functionality is localized where it is usedFunctionality is localized where it is used

InheritanceInheritance

nn Improves program organizationImproves program organization

nn Fosters code reuse, sharing of librariesFosters code reuse, sharing of libraries

eMacaoeMacao--1414--0303--9090

SummarySummary

OO methods regard the world as composed ofOO methods regard the world as composed ofinteracting entitiesinteracting entities

nn Identify abstractions of entitiesIdentify abstractions of entitiesàà classesclasses

nn Identify relationships between entitiesIdentify relationships between entitiesàà association,association,inheritance, etc.inheritance, etc.

nn Hide details of implementation from clients, allowHide details of implementation from clients, allow

different implementations of interfacesdifferent implementations of interfacesàà polymorphismpolymorphism

OO methods have the potential to result in higherOO methods have the potential to result in higherquality, more modular & reusable softwarequality, more modular & reusable software

Page 46: oomd1

8/8/2019 oomd1

http://slidepdf.com/reader/full/oomd1 46/46

eMacaoeMacao--1414--0303--9191

ReferencesReferences

[Boo94] Grady[Boo94] Grady BoochBooch,, Object Object - - Oriented Analysis and Design With Oriented Analysis and Design With 

Applications Applications , Benjamin Cummings, 1994, Benjamin Cummings, 1994

[BRJ99] Grady[BRJ99] Grady BoochBooch, James, James RumbaughRumbaugh,, IvarIvar Jacobson,Jacobson, The Unified The Unified 

Modeling Language User Guide Modeling Language User Guide , Addison Wesley, 1999, Addison Wesley, 1999

[Mey97] Bertrand Meyer,[Mey97] Bertrand Meyer, Object Object - - Oriented Software Construction Oriented Software Construction , 2, 2ndnd ed.,ed.,

Prentice Hall, 1997Prentice Hall, 1997

[MK04] Jim[MK04] Jim McKimMcKim,, Object Oriented Programming and Design: Object Object Oriented Programming and Design: Object 

Oriented Concepts Oriented Concepts , 2004, 2004

[Pap01][Pap01] PetraqPetraq PapajorgjiPapajorgji,, Introduction to Object Oriented Design and Introduction to Object Oriented Design and 

Unified Modeling Language (UML)Unified Modeling Language (UML), 2001, 2001

[RBPEL91] James[RBPEL91] James RumbaughRumbaugh, Michael, Michael BlahaBlaha, William, William PremerlaniPremerlani,,Frederick Eddy, WilliamFrederick Eddy, William LorensenLorensen,, Object Object - - Oriented Modeling and Oriented Modeling and 

Design Design , Prentice Hall, 1991, Prentice Hall, 1991

[Sch00][Sch00] Douglas C. SchmidtDouglas C. Schmidt,, Object Object - - Oriented Design and Programming Oriented Design and Programming ,,

20002000