9. Object-Oriented design and UML (Unified Modeling Language)
description
Transcript of 9. Object-Oriented design and UML (Unified Modeling Language)
9. Object-Oriented design and UML (Unified Modeling Language)
In this part you will learn:Definition of Object-Oriented designEncapsulationInformation hidingClasses and ObjectsState retentionObject identityMessagesInheritanceAssociationPolymorphismGenerosity
All of these concepts are represented with UML notation.
8.1 Definition of Object-Oriented design
Before giving a definition, let’s first understand the difference in the principles of structured design and object-oriented design.
Structured design: function-oriented or
model-oriented.
For example, a cash dispenser is modeled as follows:
Customer
customer-request
cash-card
password
card-password
Receive-Request
Check-Password
Withdraw
Show-Balance
withdraw-request
show-balance-request
correct-pass
incorrect-pass
current-balance
over-balance
requested-amount
account
Object-oriented design: object-oriented.
Example,
Customer
AccountInterface
account: Accountcard-password
customer: Set Customer
Receive-RequestCheck-Password
WithdrawShow-Balance
balanceaccount-number
Set-BalanceGet-BalanceGet-Account-Number
relation1relation2
It is difficult to give a definition for Object-Oriented design
mathematically, but we can describe what object-orientation
is about in an informal manner.
Description: object-oriented design (OOD) means to build programs by means of designing objects and their relations.
In other words, in OOD identification and design of objects and their relations are the most important tasks. If all of the necessary objects and their relations are well designed, the entire program will be well designed.
What is an object in general
Description: an object is a material thing that can be seen or touched.
Examples:A watch: a place to show time + operations (e.g., (1) adjust time, (2) set alarm, (3) adjust dates)A TV set: a screen + operations (e.g., (1) change channels, (2) adjust volume, (3) Change modes)A book: a set of pages, but no operations to offer.A person: physical body + operations (e.g., (1) eat, (2) walk, (3) drink, (4) sleep)
8.2 EncapsulationObject-oriented encapsulation is the packaging of
operations and attributes representing state into an object type so that state is accessible or modifiable only via the interface provided by the encapsulation.
Attributes are represented by instance variables in a Java class.
Operations are like methods of a Java class.
State is a collection of instance variables together with their values.
Interface are like public methods of a Java class.
The illustration of encapsulationclass Calculator { private int reg; public Calculator() { initialize reg; } //constructor of the class public int Add(int i) { reg = reg + i; } public int Subtract(int i) { reg = reg – i; } private int Multiply(int i) { reg = reg * i; } }
Attribute: regOperations: Add, Subtract, MultiplyState: reg;Interface: Add, Subtract
The change of interfaceclass Calculator { private int reg; public Calculator() { initialize reg; } //constructor of the class public int Add(int i) { reg = reg + i; } public int Subtract(int i) { reg = reg – i; } public int Multiply(int i) { reg = reg * i; } }
Attribute: regOperations: Add, Subtract, MultiplyState: reg;Interface: Add, Subtract, Multiply
8.3 Information hidingInformation hiding is the use of encapsulation to restrict from external visibility certain information or implementation decisions that are internal to the encapsulation structure.
Information means:Attributes. (1) the implementation details of attributes, including how they are stored and named, are hidden, (2) they are usually not directly accessible by outside operations. Implementation details of all the operations.
For example:
class Calculator {
private int reg; //hidden attribute
public Calculator() {
initialize reg;
} //constructor of the class
public int Add(int i) { //interface operation
reg = reg + i;
}
public int Subtract(int i) { //interface operation
reg = reg – i;
}
public int Multiply(int i) { //interface operation
reg = reg * i;
}
}
8.4 Classes and objects
Description(class): a class can be understood in both static and dynamic views:
Static view: a class is a specification that defines the attributes and operations which its every object shares. Therefore, a class is what you design and program.
Dynamic view: a class is a collection of objects that share the same features (i.e., with the same kinds of attributes and operations). Therefore, objects are what you create (from a class) at run-time.
Description(object): an object is an instance of a class. In other words, an object can be instantiated from a class.
Graphical illustration of class and objects: x1, x2, and x3 represent objects of the class that has three operations Op1, Op2, and Op3.
Op1
Op2
Op3
x1
x2
x3
class
Graphical representations of classes and objects in UML
UML: Unified Modeling Language.
Initially, UML was proposed by Bouch, Jacobson,
and Rumbaugh, and then standardized by
Object Management Group (OMG).
or
SomeClass SomeClass
Symbol for a class in its full and abbreviated forms.
Attributes
Methods
someObject:SomeClass someObject: SomeClass
Symbol for an object in its full and abbreviated forms.
Attributes
Methods
Example of class
/ age means the attribute is not directly settable, it is read-only variable.Keywords: in, out, inout.in argument: input of the method. in is usually omitted. out argument: output of the method.inout argument: both input and output of the method.
Person
name: StringdateOfBirth: Date
height: Length/ age: Duration
getName(out name: String)
setName(name: String)
getHeight(date: Date, out height: Length)
setHeight(data: Date, height: Length)
Example of object
realPerson: Person
Mike25.2.1965
17520
getName(out name: String)
setName(name: String)
getHeight(date: Date, out height: Length)
setHeight(data: Date, height: Length)
Suppose that three objects are instantiated from class
Person:
object1 object2 object3
person1
var name var dateOfBirth var height var age
setNamegetNamegetHeightsetHeight
person2
var name var dateOfBirth var height var age
setNamegetNamegetHeightsetHeight
person3
var name var dateOfBirth var height var age
setNamegetNamegetHeightsetHeight
Since the methods are program codes, and can be
shared by all of the objects instantiated from the
same class, the implementation of objects of class
Person at run time is in fact as follows:
methods object1 object2
setNamegetNamegetHeightsetHeight
var name var dateOfBirth var height var age
var name var dateOfBirth var height var age
var name var dateOfBirth var height var age
object3
8.5 State retention
Definition (state): state of an object is a set of attributes, which is subject to change during the operation of the program.
For example, the object realPerson has a state:
name = “Mike”
dateOfBirth = 25.2.1965
height = 175
age = 20
Description: state retention means that the state of an object is retained after it has finished executing its methods. In other words, an object sustains its state until it dies (e.g., garbage collection).
This point is different from a function in C and a procedure in Pascal: when calling a function or procedure, the state of the function or procedure is created, and when the function or procedure terminates, its state vanishes.
8.6 Object identity
Object identity is the property by which each object
(regardless of its class or current state) can be
identified and treated as a distinct software entity.
In other words, every object has a unique identity.
Such an object identity is called object reference
or object handle. Such a handle is decided when
an object is created with the new operator. It is a common
way to use the address of the object (the starting memory
unit of its attributes) as its handle.
Example
Person p1 = new Person();
Person p2 = new Person();
602237
142857
P1
P2
objects
p2 = p1;
602237
602237
P1
P2
object
This object has died.
8.7 Messages
Description: A message is the vehicle by which a sender object obj1 conveys to a target object obj2 a demand for object obj2 to apply one of its methods.
obj1 obj2obj2.m1(in a, out b)
Sending a message is like calling a traditionalfunction or procedure: call m1(obj2, a, b)
8.7.1 Message structure
The general structure of a message is:
obj2.m1(in a, b, c, out x, y, z)
method name output arguments
target object input arguments
message
8.7.2 The roles of objects in messages
An object may play the following roles in messages:
• The sender of a message (e.g., obj1).
• The target of a message (e.g., obj2).
• Pointed to by an argument passed back or forth in a message (e.g., obj).
obj2.m1(in a, b, c, out x, y, z, inout obj)
obj1 obj2
8.7.3 Types of messages
There are three types of messages:
Informative messages
Interrogative messages
Imperative messages
Informative messages
An informative message is a message to an object that provides the object with information to update itself. It is also known as update, forward, or push message.
For example,
person1.setName(name1)
In this message object person1 is informed that its name is changed to name1. Therefore, person1 needs to update its name using the method setName.
Interrogative message An interrogative message is a message to an object
requesting it to reveal some information about itself. (It is also known as a read, backward, or pull message.).
For example, person1.getName()
Object person1 is requested to tell its name by calling its getName method.
Imperative message An imperative message is a message to an object t
hat requests the object to take some action on itself, another object, or even the environment around the system. (It is also known as a force or action message.)
For example, person1.sendName(obj); This message requests object person1 to send its n
ame to another object obj of class Person.
8.8 Inheritance
Question:In your design, if you wrote a class C and then later discovered a class D that was almost identical to C except for a few extra attributes or operations, what would you do? Example: class C { class D { T1 a1; a1, a2, method1, and T2 a2; method2 of C are method1; needed here; method2; method3; } }
Two solutions:
(1) Duplicate all the attributes and operations of C and put them into D.
class C { class D {
T1 a1; T1 a1;
T2 a2; T2 a2;
method1; method1;
method2; method2;
} method3;
}
(2) Have class D use the attributes and operations of the class C. This solution is called inheritance.
Description: Inheritance (by class D from C) is a mechanism that allows a class D to have implicitly the attributes and operations of class C, as if those attributes and operations had been defined upon D itself.
In other words, through inheritance, objects of class D can make use of attributes and operations that would otherwise be available only to objects of class C.
Inheritance represents another major way in which
object orientation departs from traditional systems
approaches. It effectively allows you to build
software incrementally in this way:
First, build classes to cope with the most general case.
Then, in order to deal with special cases, add more specialized classes that inherit from the first class. These new classes will be entitled to use all the operations and attributes (both class and instance operations and attributes) of the original class.
For example,
Employee
name: StringdateOfBirth: Date
setName(name: String)getName(out name: String)
getDateOfBirth(out dateOfBirth: Date)setDateOfBirth(data: Date,)
Professor
Lab: nat0courses: seq of String
getLab()setCourses(newCourses: seq of String)
Administrator
dvision: String
setDivision(newDivision: String)
getDvision()
Definition: if class B inherits from class A, B is known as a subclass of A, and A is a super class of B.
Inheritance is transitive. That is, if C inherits from
B, and B inherits from A, then C will definitely inherit from A.
In UML, the inheritance hierarchy: classes B, C, and D inherit from A, class E inherits from C, are represented by the following graphical notation.
Class inheritance hierarchy:
A
B C D
E
Multiple inheritanceDescription: multiple inheritance is a mechanism
that allows a class to inherit from more than one super classes. For example, a Professor can be an Employee and an Employer simultaneously.
Employee Employer
Professor
The problem in multiple inheritance
The problem is the conflict of attribute or operation names in super classes.
Both super classeshave the attribute: name,and the method: getName.
Employee Employer
Professor
nameage
namecapital
getName()getName()
lab
getLocation()
Solutions for the problem in multiple inheritance
Resolve the conflict of attribute and operation names in the super classes.
Run time error
Check by the complier
Disallow the multiple inheritance (e.g., Java)
Exercise 7(1) Describe the relationship between objects and cl
asses.
(2) Explain what is object-oriented design.
(3) Suppose Animal be the super class of classes Dog, Cow, and Cat; Cat is the super class of classes WhiteCat and BlackCat. Draw the class inheritance hierarchy of these classes.
8.9 AssociationDescription: an association (known as binary association)
represents a relation between two classes, where a relation is a set of relationships between instances of the classes.
Example: let LibraryPatron and LibraryBook be two
classes.
An association between them is Borrowing, a set of relationship links stating which patron is currently borrowing which book. As an example, the Borrowing association may contain the following four links:
Jeff is borrowing Program Design
Chris is borrowing Programming in Java
John is borrowing Software Engineering
Jim is borrowing Formal Methods
Notice that borrowing represents a bunch of links, each reflecting a relationship between two instances of two classes.
8.9.1 The basic UML notation for associations
The following figure shows three associations: Employment between classes Person and Company; Residence between Person and County; and Site between County and Company.
Company
County
Person Employmentemployee
employerresident
0..*Residence
1..1 1..*
Site
0..*
0..1
0..*
The meaning of each component of this diagram:The box represents a class.The line between two classes represents a relation (association) between the two classes. A relation has a name attached to the line. The name of a relation usually starts with a capital letter, like Employment and Residence.The role of a class in the association diagram may appear beside it at the end of a association line, such as employee and residence.The multiplicity of the association appears at the ends of each line. For example, 0..1 at the end of Employment association, beside class Company, means that a given person is an employee of 0 or 1 company, while 0..* at the end of the same association line beside class Person means that a given company is an employer of 0 to many (denoted by an asterisk *) persons.
Some important points about UML notation for associations:• The name of an association should be a noun, because it
represents a class in implementation, as we will explain later.
• UML doesn’t insist on a name for an association, but it is a good discipline to give a name for each association in general.
• UML doesn’t require role names of classes either. The role names should be given whenever it is necessary in avoiding the confusion of the meaning of associations.
• The multiplicity can be abbreviated. For example, 0..* can be written as *, and 1..1 can be written as 1. But notice that 0..1 cannot be written as 1.
8.9.2 Associations depicted as classes
An association between two classes can be depicted
as a class. This also indicates a way to implement an
association in the program code.
EmploymentPerson Company*
1employee
employer
Employment is depicted as a class in which Person and Company may be used to declare instance variables (representing attributes of its objects), like employee, employer, startDay, and terminationDay.Operations may be defined in this class for providing necessary services, such as setStartDay() and
GetTerminationDay().
Person Company*
1employee
employer
Employment
employee:Personemployer:CompanystartDay: Date
terminationDay: Date
setStartDay()GetTerminationDay()
8.9.3 Higher-order associations
A higher-order association is an association among
more than two classes.
A diamond is used to represent a higher-order
association.
Example, the following Figure shows part of a
purchasing model for buying items from vendors. In this
business, the unit price depends on three factors: the item type
(the product), the company that is selling it (the vendor), and the
quantity of items you purchase (the price-break level).
We build a three-way association among ItemType, Company, and PurchasedQuantity, in order to have a suitable home for the unitPrice attribute, which is determined by the instances of those three classes.
Company ItemType*
*vendor
product
ItemPurchaseCatalog
unitPrice: Money
priceBreakLevel*
PurchasedQuantity
getPrice(...)
The operation getPrice(…) may be implemented simply in Java as follows:
public void getPrice(ItemType item, Company vendor, PurchasedQuantity quantity){ if (item.getType() = “Pen” && vendor.getName() = “NEC” && quantity.getNumber() > 20) unitPrice = Exp1; else unitPrice = Exp2;}
8.9.4 Navigability of associations
Navigability of an association is the ability of
showing the direction of the association between the
two classes.
Example 1:
EmploymentPerson Company*
1employee
employer
This diagram shows that classes Person and Company havethe association Employment, and associated Company object can be easily and quickly (supported by implementation) found from a Person object.
EmploymentPerson
Company*
1employee
employeremployer: Company
...
Such a navigability can be built into each Person objectby referring to a Company object, as shown in thefollowing diagram.
Example 2:
EmploymentPerson Company*
1employee
employer
This diagram shows that classes Person and Company havethe association Employment, and associated Person object can be easily and quickly (supported by implementation) found from a Company object.
Such a navigability can be built into each Company objectby referring to a set of Person objects, as shown in thefollowing diagram.
EmploymentPersonCompany
*
1employee
employer employees: Set <Person>
...
Where Set <Person> means a set of Person objects.
Example 3:
EmploymentPerson Company*
1employee
employer
This diagram shows that classes Person and Company havethe association Employment, and associated Person object can be easily and quickly (supported by implementation) found from a Company object, and vice versa.
Such a navigability can be built into both a Company objectby referring to a set of Person objects and a Person object by referring to a Company object, as shown in thefollowing diagram.
EmploymentPerson Company
*
1employee
employeremployer: Company
...
employees: Set <Person>
8.10 . Whole/Part associations
The whole/part association is an association between classes.
There are two kinds of whole/part associations:
composition and aggregation.
8.10.1 Composition
Description: if an object A is comprised of objects A1, A2, and A3, we say A is the composition of A1, A2, and A3.
Examples:
(1) A dog is a composition of a head, a body, a tail, and four legs.
(2) A university is a composition of departments, professors, students, administration officers, buildings, and equipments.
(3) A shop is a composition of goods, shop assistants, and a building.
Usually, in a composition the “whole” is called the composite object while the “part” is called the component object.
Example:
A is the composite object while A1 (the same as for A2 and A3) is the component object. Such a composition association is depicted in UML by the following diagram.
A3-ClassA2-ClassA1-Class
A-Class
1 1 1
Such a composition can be implemented bydeclaring three instance variables in A-Class:
A1: A1-Class; A2: A2-Class; A3: A3-Class;
Important characteristics of composition:(1) The composite object does not exist without its
components. For example, a dog does not exist without a head.
(2) The component objects of a composite object may belong to different classes. For example, a head, a body, a leg, a tail of a dog usually belong to different classes.
8.10.2 Aggregation
Description: aggregation is a group/member association.
Examples:
(1) A street is an aggregate of houses.
(2) A forest is an aggregate of trees.
(3) A club is an aggregate of club members.
(4) A book is an aggregate of chapters.
In the aggregation association, the “whole” is called the aggregate object while the “part” is called the constituent object.
Important characteristics of aggregation:
(1) The aggregate object may potentially exist without its constituent objects (which is different from a composite object in a composition). For example, a street may still exist even if all of its houses are destroyed.
(2) The constituent objects of a typical aggregate object belong to the same class (which is different from a component object in a composition). For example, an aggregate object forest consists of trees that belong to the same class.
The UML representation of aggregation:
Chapter
Book
0..*
0..*textPart
Person
Club
0..*
0..*member
These two aggregations can be implemented by
declaring an instance variable in each of classes
Book and Club.
In class Book:
chapters: Set <Chapter>
In class Club:
members: Set <Person>
8.11 PolymorphismThe word “polymorphism” comes from two Greek
words that mean, respectively, “many” and “form”.
Polymorphism is an important feature of object-
oriented programs. It is realized due to the class
inheritance.
Description: polymorphism is the facility by which a singleoperation or attribute name may be defined upon more than one class and may take on different implementations in each of those classes.
Example:
Polygon
area
getArea()
Rectangle Triangle Diamond
getArea() getArea() getArea()
Rectangle Triangle Diamond
Polygon
In this example, Polygon includes three specific shapes: rectangle, triangle, and diamond.
We define each shape as a class, and build the classhierarchy on the previous page. In this hierarchy Polygon is the super class, which has an attribute area and an operation getArea().
Classes rectangle, triangle, and diamond are all subclasses of Polygon. They all inherit Polygon’s attributes
and operation, including getArea(). However, the implementation of the getArea() on each subclass may be different because the formula for computing the area of each specific shape may be different. The
Formulas for computing areas for different shapes:
(1) Rectangle:
area = length * width
(2) Triangle:
area = (base * height) / 2
(3) Diamond:
area = (diagonal-line1 * diagonal-line2) / 2
Description: overriding is the redefinition of an operation defined on a class C in one of its subclasses.
For example,
getArea() defined in class Rectangle is an overriding of getArea() defined in class Polygon.
getArea() defined in class Triangle is also an overriding of getArea() defined in class Polygon.
getArea() defined in class Diamond is also an overriding of getArea() defined in class Polygon.
The explanation of polymorphism: an example of Java method:
void A() { Polygon p = new Polygon(); Triangle t = new Triangle(); Diamond d = new Diamond(); … if (e) p = t; else p = d; … p.getArea(); …}
p.getArea() has the following possbilities: (1)p is bound to an object of Triangle, and get
Area() defined in Triangle is executed.(2)p is bound to an object of Diamond, and ge
tArea() defined in Diamond is executed.(3)p is bound to an object of Rectangle, and g
etArea() defined in Retangle is executed.(4)p is bound to an object of Polygon, and get
Area() defined in Polygon is executed.
Dynamic binding (or run-time binding) is the technique by which the exact piece of code to be executed is determined only at run-time (as opposed to compile-time). The principle of such a binding is to execute the operation of the current object, if it is defined in the corresponding class of this object, then, if not, to execute the same operation defined in its super class.
8.12 Genericity class A {
T v1;
int v2;
void M1(T w)
{
…
}
…
}
More general class
A simple example of class:
class A {
Triangle v1;
int v2;
void M1(Triangle w)
{
…
}
…
}
Genericity is such a construction of a class C that one or more of the classes that it uses internally is supplied only at run-time (at the time that an object of class C is instantiated).
Such a class C is usually called parameterized class (also known as generic class). A parameterized class is represented graphically in UML as follows:
Stack
Push(element:T)Pop(out element:T)
T
PushPop
element
Stack
Declare variables with a parameterized class:Example: s: Stack <int>;This declaration means that variable s will be used as a stack
of integers. Define a specific class with a parameterized class in UML:
Stack
Push(element:T)Pop(out element:T)
T
IntStack
<< bind>>
<int>
Then the class IntStack can beused to declare variables:
s: IntStack;
Exercise 8
(1) Suppose the classes Student and University have a binary association Study, draw a UML association diagram to describe this association. In this diagram you must show appropriate multiplicity.
(2) Let class A be the composition of classes B, C, and D. Draw an appropriate UML diagram to describe this composition.