View
1
Download
0
Category
Preview:
Citation preview
CISC 323, winter 2003, OOP/UML 1
First Topic: OOP and UML
Plan for this topic: review OOP and introduce UML
Recall three basic concepts of OOP:1. encapsulation2. inheritance3. polymorphism
This course uses Java as its OO programming language.Concepts will apply to other OO languages.
Reading on OOP: Bahrami chapter 2If you need review on Java details, consult any Java text or
Thinking in Java on the web.
CISC 323, winter 2003, OOP/UML 2
ModelingEngineers build models of objects • physical models• different kinds of paper models (diagrams, blueprints)
Software designers build models of softwareReasons for models:• simplified version of final product: easier to understand• helps you record & communicate design decisions• expose errors & possible simplifications• provides documentation afterwards for maintenance
Single model may not be enough:• different views• different levels of detail
CISC 323, winter 2003, OOP/UML 3
UMLUML = Unified Modeling Language
Notation for modeling software
UML includes many kinds of diagrams, many kinds of components & connectors
You don't have to know all details of UML
Slides are a good guideline for how much to know
Reading from Bahrami: Chapter 5, up to and including Section 5.8.1.1 (UML Sequence Diagram)
CISC 323, winter 2003, OOP/UML 4
UML DiagramsMany different kinds of UML diagrams.
For now, we will discuss:• Class diagrams – models classes of objects
• requirements analysis: real world objects• detailed design: software objects
• Use case diagrams – models a use of the system• Sequence diagrams – models interaction of system and
environment
We will introduce class diagrams in parallel with the OOP review, then return to use case and sequence diagrams
CISC 323, winter 2003, OOP/UML 5
Important Point About UMLUML is not a programming languagediagrammatic language meant to be read by humans
may be many options, shades of meaning
CISC 323, winter 2003, OOP/UML 6
Java Classes: Quick ReviewA class is a template for a kind of object
objects of the class have attributes (instance variables, fields) which contain data
objects also have methods for using and modifying data inside the objects
attributes and methods may be static (belong to class, not individual objects)
CISC 323, winter 2003, OOP/UML 7
Example Class: Employee
Purpose of class: keep track of an employee for payroll purposes
Very simple class diagram:
Employee
No information about attributes & methods
CISC 323, winter 2003, OOP/UML 8
Attributes
What data will we store in Employee object?• basic information (name & job title)• hourly wage• amount of pay earned so far
Expand class diagram to include attributes:
Employee
name: StringjobTitle: Stringwage: doublepayOwed: double
CISC 323, winter 2003, OOP/UML 9
Java Code/*** A class to record information about employees* for payroll purposes.*/
public class Employee {/** the employee's name */private String name;/** the employee's job title */private String jobTitle;/** the hourly wage for the employee */private double wage;/** the amount of money the company currently
owes the employee */private double payOwed;
CISC 323, winter 2003, OOP/UML 10
Methods for Employee Class
What do we want to do to/with an Employee?• create & initialize an Employee object (constructor)• record pay for hours worked• find out how much we currently owe the employee• zero the pay owed (after issuing paycheck)
CISC 323, winter 2003, OOP/UML 11
Put Methods in Class Diagram
Add third section for methods
Employeename: StringjobTitle: Stringwage: doublepayOwed: double
pay()amountToPay()zero()
Haven't decided on method details yet(parameters & return value)
CISC 323, winter 2003, OOP/UML 12
First Method/**
* Pays the employee for a number of hours
* worked. This increases the amount of pay
* owed to the employee.
*
* Parameter: the number of hours worked
*/
public void pay(int hours) {
// pay for these hours
double newPay = hours * wage;
payOwed += newPay;
} // end pay
CISC 323, winter 2003, OOP/UML 13
Another Method/**
* Returns the amount of pay owed to this
* employee.
*
* Return value: the pay owed
*/
public double amountToPay() {
return payOwed;
} // end amountToPay
CISC 323, winter 2003, OOP/UML 14
Yet Another Method
/**
* Zeros the amount of pay owed to this
* employee. Call this method after you write
* the employee a cheque for a pay period.
*/
public void zero() {
payOwed = 0;
} // end zero
CISC 323, winter 2003, OOP/UML 15
More Detailed Class Diagram
Now we've decided on method details, can include them in third section of diagram
Employee
name: StringjobTitle: Stringwage: doublepayOwed: double
void pay(int hours)double amountToPay()void zero()
CISC 323, winter 2003, OOP/UML 16
Different Class DiagramsSeveral class diagrams for the Employee class:
EmployeeEmployee
name: StringjobTitle: Stringwage: doublepayOwed: double
All are correct.Which to use?depends on
circumstances
Employee
name: StringjobTitle: Stringwage: doublepayOwed: doublevoid pay(int hours)double amountToPay()void zero()
Employee
name: StringjobTitle: Stringwage: doublepayOwed: double
pay()amountToPay()zero()
Employee
pay()amountToPay()zero()
CISC 323, winter 2003, OOP/UML 17
Reminder: Using the Employee Class// in another class:
Employee muldur =
new Employee("Muldur", "agent", 25);
muldur.pay(8);
muldur.pay(10);
System.out.println("amount to pay Muldur: $"
+ muldur.amountToPay());
output is: amount to pay Muldur: $450
CISC 323, winter 2003, OOP/UML 18
Reminder: Information Hiding
Code made all attributes are private instance variables – i.e.:private double payOwed;
can't access or change muldur.payOwed directlyinstead, use methods pay, amountToPaygives us control over how the user can change the object
CISC 323, winter 2003, OOP/UML 19
Access Modifiers in Class Diagram
If you want to show whether attributes are private, public or protected: use abbreviations
+: public#: protected-: private
Employee
-name: String-jobTitle: String-wage: double-payOwed: double
If you don't use one of these modifiers, you are choosing not to specify (not using a default)
CISC 323, winter 2003, OOP/UML 20
Relationships Between Classes
UML Class Diagrams can express relationships between classesSuppose we have a class called OfficeEach Employee is associated with an OfficeLine between classes represents an association:
Employee Office
CISC 323, winter 2003, OOP/UML 21
Association Name
We can give a name to the association by putting a label in the middle of the line.
A triangle by the name shows the direction for the name:An Employee "worksIn" an Office.
worksInEmployee Office
CISC 323, winter 2003, OOP/UML 22
Association Roles
In defining an association between two classes, we can give names to the roles of either or both classes:
Employee Officeoccupant workplace
We can name the association and the roles if we want to:
worksInEmployee Officeoccupant workplace
CISC 323, winter 2003, OOP/UML 23
What an Association Means
An association between Employee & Office means a logical connection, not any particular implementation.
Possible implementations:• each Employee contains pointer to an Office• each Office contains pointer to an Employee• both of above• central table or database of (Office, Employee) pairs• etc.
CISC 323, winter 2003, OOP/UML 24
Navigability
Employee Office
If we put an arrow on an association, it means there is a way tonavigate from one class to another.
Above diagram means software will provide a way to go from an Employee to the Employee's Office
Could mean each Employee has pointer to his/her office
Or could mean some kind of central table
CISC 323, winter 2003, OOP/UML 25
Caution About Connections
UML class diagrams use many different kinds of connections:
Careful about which you use; all have different meanings!
CISC 323, winter 2003, OOP/UML 26
Associations & Multiplicity (1)Typical arrangement:
• each employee has just one office• some offices are private, some shared by 2-3 employees
Other possiblilities:• all offices are private• some employees have multiple roles, different offices
for each• contract employees with no offices• vacant offices
UML we've shown doesn't specify
CISC 323, winter 2003, OOP/UML 27
Associations & Multiplicity (2)
Employee Office1 1worksIn
One-to-one correspondence.Every employee has one private office.One employee to an office.One office per employee.
CISC 323, winter 2003, OOP/UML 28
Associations & Multiplicity (3)
Employee 1..* 1worksInOffice
Many-to-one correspondence.Every employee has one office.An office can have more than one employee in it, but no
vacant offices
CISC 323, winter 2003, OOP/UML 29
Associations & Multiplicity (4)
Employee Office* 1worksIn
Many-to-one correspondence.Every employee has one office.An office can have any number of employees, or be
vacantNote: * is equivalent to 0..*
CISC 323, winter 2003, OOP/UML 30
Associations & Multiplicity (5)
Employee1 0..1worksIn
Office
Every office is private: one employee.Some employees have no office.
CISC 323, winter 2003, OOP/UML 31
Associations & Multiplicity (6)
Employee 1..3 0..2worksInOffice
An office has from 1 to 3 people in it.An employee can have no office, one office, or two offices.
CISC 323, winter 2003, OOP/UML 32
Reflexive Associations
An association can connect a class to itself:
Person
Parent
*
0..2
Recall open arrows for navigability.Means can go from person to parent or person to children.Parent can have any number of childrenPerson can have up to 2 parents recorded
CISC 323, winter 2003, OOP/UML 33
Composition
containsCD Track
1 1..*
A CD contains one or more tracks.The filled diamond means composition.A CD is composed of Tracks.A Track is part of a CD – won't exist on its own.Tracks can belong to only one CD.If you delete the CD, the Tracks go away too.
CISC 323, winter 2003, OOP/UML 34
Another Way to Show Composition
CD
Track 1..*
CISC 323, winter 2003, OOP/UML 35
Aggregationcontains
A hollow diamond means aggregation.Similar to composition: a CD is made up of tracks.A Song may belong to more than one CDWith aggregation, it's possible to delete a CD without
all the Songs going away.Difference are often subtle – don't sweat it!
CD Song* 1..*
1..*11*
Track
CISC 323, winter 2003, OOP/UML 36
Qualifiers
A qualifier is an attribute of an association:a piece of information about the association betweentwo objects
CD
track number
*
1..*
Song
CISC 323, winter 2003, OOP/UML 37
Another Example
Project & Resource Management System
Project1
1..*
Activity Skill
Task Resource
1 *
1..*Assigned To* 1
*
Alhir, Sinan Si, UML in a Nushell, O'Reilly & Associates, 1998, pp. 76-77
CISC 323, winter 2003, OOP/UML 38
Association Classes
An Experience object contains information about a(Skill, Resource) pair:
expert or novice, years of experience, etc.
Skill
*Experience
*Resource
CISC 323, winter 2003, OOP/UML 39
Object Diagrams
Similar to class diagrams. Shows objects rather than classes.Provides a "snapshot" of the system at some moment in time.
Mary: Employee
name = "Mary"jobTitle = "manager"
wage = 35payOwed = 280
George: Employee
name = "George"jobTitle = "typist"
wage = 20payOwed = 160
Office
building = "Goodwin"number = 123
worksIn
worksIn
CISC 323, winter 2003, OOP/UML 40
Back to Employee Class
Employee
name: StringjobTitle: Stringwage: doublepayOwed: doublevoid pay(int hours)double amountToPay()void zero()
What if we want another kind of employee?
CISC 323, winter 2003, OOP/UML 41
Salesperson
A salesperson is paid by the hour like all employeesalso gets a commission: percentage of sales made
How to handle this in our program?We want a class like Employee with added features:
rate of commission (attribute)way to record a sale (method)
CISC 323, winter 2003, OOP/UML 42
Option 1: Change Employee
Change the Employee classAdd commission rate & method for recording saleFor many employees, commission rate is zeroProblems:
extra computations & storage for alldoesn't relect our mental picture
CISC 323, winter 2003, OOP/UML 43
Option 2: Copy of Employee
Create a separate class called Salesperson. • Copy all attributes & methods from Employee • add commission stuff
Problem: lots of repeated code. • more typing• more chance to make mistakes• 2 classes to maintain• still doesn't reflect our mental picture: classes are
related
CISC 323, winter 2003, OOP/UML 44
Better Way: Use Inheritance
Java lets us extend a class: • create a new class which adds to another class • or changes the other class in certain ways
Java Syntax:public class Salesperson extends Employee {
// extra attributes
// extra methods
} // end class Salesperson
Meaning:• contains all methods & attributes from Employee• plus the extras we added.
CISC 323, winter 2003, OOP/UML 45
Salesperson Class
public class Salesperson extends Employee {
// constructor(s)....
// The salesperson's commission rate. // Must be between 0 and 1.private double rate;
// Pays commission for a salepublic void payForSale(double saleAmount) {payOwed += rate * saleAmount;
} // end payForSale
} // end class Salesperson
CISC 323, winter 2003, OOP/UML 46
UML For InheritanceArrow with hollow triangle
head representsgeneralization (inheritance).
Employee
name: StringjobTitle: Stringwage: doublepayOwed: doublevoid pay(int hours)double amountToPay()void zero()
Salesperson
rate: double
void payForSale(double amt)
CISC 323, winter 2003, OOP/UML 47
Vocabulary
Employee is the superclass or parent class Salesperson is the subclass or child class Salesperson extends Employee.Salesperson inherits attributes & methods from Employee.
Salesperson is a derived class(derived from Employee)
CISC 323, winter 2003, OOP/UML 48
Using Salesperson
Salesperson loman = new Salesperson("Willy Loman", "salesperson", 10, 0.2);
loman.pay(10); loman.payForSale(400);System.out.println("amount to pay Willy Loman: $"
+ loman.amountToPay());
Notice: loman is object of class SalespersonWe called loman.amountToPay: method from EmployeeAlso called loman.payForSale: method from Salesperson
CISC 323, winter 2003, OOP/UML 49
Another Derived Class
In our company, only executive employees can receive bonuses
A bonus is a one-time payment, not based on hoursHow to represent?Derive another class from Employee
CISC 323, winter 2003, OOP/UML 50
UML: Two Subclasses
Employee
name: StringjobTitle: Stringwage: doublepayOwed: doublevoid pay(int hours)double amountToPay()void zero()
Salesperson
rate: double
void payForSale(double amt)
Executive
void payBonus(double amt)
CISC 323, winter 2003, OOP/UML 51
One More Subclass
In our company, most employees don't get overtime.Some unionized employees do get overtime:
1.5 times their salary for hours more than 8 in a day
Define new class: UnionizedNo new attributes or methodsChange in the way the pay method works –
overrides the pay method
CISC 323, winter 2003, OOP/UML 52
Unionized Classpublic class Unionized extends Employee {
// constructor(s)....
public void pay(int hours) {// Increase any hours > 8 by 50%if (hours > 8) {
int extra = hours - 8;hours += extra / 2;
} // end if// now pay as beforepayOwed += hours * wage;
} // end pay
} // end Unionized
same as pay method fromparent class (Employee)
super.pay(hours);
replace
CISC 323, winter 2003, OOP/UML 53
UML: Three SubclassesEmployee
name: StringjobTitle: Stringwage: doublepayOwed: doublevoid pay(int hours)double amountToPay()void zero()
Salesperson
rate: double
void payForSale(double amt)
Executive
void payBonus(double amt)
Unionized
void pay(int hours)
CISC 323, winter 2003, OOP/UML 54
Multiple Inheritance (1)
Another kind of employee: executive salespersonGets commission, also eligible for bonusesHow to implement?New class could be subclass of Salesperson or ExecutiveWe want it to inherit features of both
CISC 323, winter 2003, OOP/UML 55
Multiple Inheritance (2)
In some languages (C++), a class can extend more than one other class: inherits attributes & methods of both
Not legal in Java! A class can have only one parent.UML allows
Employee
Salesperson Executive
ExecSalesperson
CISC 323, winter 2003, OOP/UML 56
Abstract Classes: Rationale
Employee example: parent class is useful on its ownWe instantiate Employee as well as sub-classes
Employee
SalespersonExecutive Unionized
CISC 323, winter 2003, OOP/UML 57
Abstract Classes: Rationale
Sometimes parent class is more of a placeholderAnimal
CatDog Monkey
• Would never instantiate Animal• Class is useful to hold common data & methods• Provides structure to hierarchy
- can have array of Animals
CISC 323, winter 2003, OOP/UML 58
Example: Drawing Program
Common data:• color & position
Common methods:• change position & color
Subclasses contain:• draw & resize methods• shape-specific data
Shape is an abstract classNever instantiatedIncomplete: placeholders only
for draw & resize
CISC 323, winter 2003, OOP/UML 59
Abstract Class in Java
public abstract class Shape {private <type> color;private <type> position;public void setColor(...) {<code to change color>
}public void move(...) {<code to change position>
}public abstract draw();public abstract resize(...);
} // end class Shape
abstract methods have no bodies
CISC 323, winter 2003, OOP/UML 60
Abstract Methods
Shape will never be instantiatedEach subclass must provide own version of draw()So Shape doesn't really need a body for drawUse an abstract method: header onlyWhy put draw in Shape at all??
so dynamic binding is possibleit's just a placeholdersays every subclass must define a draw method
CISC 323, winter 2003, OOP/UML 61
Abstract Classes in UML Class Diagram
Two ways to show a class is abstract
with italics: with a label:
Shape{abstract}
Shape
colorposition color
positiondraw()move() draw()
move()
Abstract methods shown in italics
CISC 323, winter 2003, OOP/UML 62
Rules
An abstract class may contain• attributes• abstract methods • concrete methods
If a class contains an abstract method:• it must be declared as an abstract class• it may not be instantiated
Concrete subclass of abstract class must overrideall abstract methods
CISC 323, winter 2003, OOP/UML 63
Concrete to Abstract
Abstract classes vary in how abstract they are.One extreme: mostly concrete
• lots of data• many concrete methods• one abstract method to be filled in by subclasses
Other extreme: completely abstract• no data• only abstract methods
Java calls this an Interface
CISC 323, winter 2003, OOP/UML 64
Interfaces
an interface is an abstract class that contains only abstract methods – no data, no concrete methods
an interface is a skeleton or template for a classspecifies methods it must have, but no real contentan interface is a skeleton or template for a classspecifies methods it must have, but no real content
CISC 323, winter 2003, OOP/UML 65
Example: StacksRecall from 121: Stack is an abstract data typeoperations: push, pop, isEmptytwo ways to implement: with array or linked list
CISC 323, winter 2003, OOP/UML 66
Stack Interfacepublic interface Stack {
public void push(int i);
public int pop();
public boolean isEmpty();
} // end interface Stack
Note: all methods in an interface are abstract.Don't need keyword abstract in declarations
Terminology:you can extend an abstract classyou implement an interface
CISC 323, winter 2003, OOP/UML 67
Array Implementationpublic class ArrayStack implements Stack {
private int elements[];private int topIndex;
public ArrayStack() {elements = new int[100];topIndex = -1;
} // end constructor
public void push(int i) {...}public int pop() {...}
public boolean isEmpty() {return topIndex == -1;
} // end isEmpty} // end class ArrayStack
CISC 323, winter 2003, OOP/UML 68
Linked List Implementationpublic class LinkedStack implements Stack {
// private attributes for a linked list
public LinkedStack() {....
} // end constructor
public void push(int i) {...}public int pop() {...}
public boolean isEmpty() {....
} // end isEmpty} // end class LinkedStack
CISC 323, winter 2003, OOP/UML 69
UML For Interfaces
"interface" is a Java conceptuseful distinction between partly & completely abstractmany other OO languages (C++) don't have interfacesin C++, Stack would be an abstract class
in UML class diagrams, show interfaces like abstract classesuse special "stereotype" to note the class is a Java
<<interface>>Stack
ArrayStack LinkedStack
CISC 323, winter 2003, OOP/UML 70
Use Case DiagramModels functionality or requirements for software, not structure of software
Describe interactions between users and system
Users can be humans or other hardware/software systems.
Vocabulary:actor: A user of a system. May be a human
or another systemuse case: A flow of events performed by the system,
initiated by an actor
CISC 323, winter 2003, OOP/UML 71
High-Level Example
Manage Resources
Manage Projects
Administer System
Project Manager
System Administrator
box represents system
stick figures are human actors
ovals are use cases
Resource Manager
<<actor>>BackupSystem
box with <<actor>> is non-human actor
CISC 323, winter 2003, OOP/UML 72
Sub-Use Cases• One use case can "use" another use case
• Useful for breaking down use case into parts, or showing common parts
• Example: to remove or update a resource, must find it
Remove Resource
Update Resource
Resource ManagerFind Resource<<uses>>
<<uses>>
CISC 323, winter 2003, OOP/UML 73
Refining Use Cases• May break down a use case into several more specific use cases• similar to extending a class in Java
Update Resource
Resource Manager
Assign Skill to Resource
<<extends>>
Unassign Skill from Resource
<<extends>>
CISC 323, winter 2003, OOP/UML 74
Another Example
from UML Notation Guide http://www.platinum.com/corp/uml/nota_11.pdf
CISC 323, winter 2003, OOP/UML 75
Notes About Use CasesUse cases do not document how a system works
Document who uses the system (actors)
Enumerates different ways the actors use the system
No detail about what happens within a use case
Each actor represents a category of users, not a single user• previous example: would be multiple customers,
salespeople, etc.
CISC 323, winter 2003, OOP/UML 76
Behavior DiagramsUse case diagrams show desired behaviorClass diagrams show classes used in software (static), not how objects behaveBehavior Diagrams capture dynamic behavior of objectsFour kinds of UML behavior diagrams:
sequence diagramscollaboration diagramsstatechart diagramsactivity diagrams
We will discuss sequence diagrams only.
CISC 323, winter 2003, OOP/UML 77
Sequence DiagramsA sequence diagram shows the interactions between several objectsModel communication between objects as messagesCan show how objects will implement a use caseSimple example: buying meal at McDonaldsuse case diagram:
Buy Meal
Customer Cashier Cook
CISC 323, winter 2003, OOP/UML 78
Details of Scenario
Three objects in scenario: customer, cashier, cook• Customer gives order to cashier• Cashier asks cook for food• Cook gives food to cashier• Cashier asks customer for money• Customer gives money to cashier• Cashier gives food to customer
Sequence diagram will show this graphically
CISC 323, winter 2003, OOP/UML 79
Objects & Lifelines
Each object represented by a boxVertical line represents time: "lifeline" of object
Customer Cashier Cook
CISC 323, winter 2003, OOP/UML 80
First Message
Represent messages between objects by solid arrows
Customer Cashier Cook
Place order
CISC 323, winter 2003, OOP/UML 81
Second Message
Time moves down in a sequence diagramSo second message goes under first one.
Customer Cashier Cook
Place orderRequest food
CISC 323, winter 2003, OOP/UML 82
More Messages
Customer Cashier Cook
Place orderRequest food
Send food
Announce price
Give money
Give food
CISC 323, winter 2003, OOP/UML 83
Conditions
Message may have a condition in brackets
Customer Cashier Cook
Place orderRequest food
Send food
Announce price
Give money
Give food[money is enough]
CISC 323, winter 2003, OOP/UML 84
Iterations
A sequence of messages may repeat
Customer Cashier Cook
Place order
Give money
Ask for more money
[until enough money]
Send foodRequest food
Announce price
Give food
CISC 323, winter 2003, OOP/UML 85
Note About Sequence Diagrams
A sequence diagram is meant to represent a fairly simple sequence of events
It doesn't have to represent whole system
Other possible MacDonald's scenarios• user orders menu item, server says it's not available• user changes mind or returns item• user doesn't have enough money• server makes mistake in computing bill
Don't try to combine all possibilities in one sequence diagram; use separate sequence diagram for each scenario
CISC 323, winter 2003, OOP/UML 86
Another Example: Elevator
Passenger Button Controller Elevator Door
press update
illuminatemove
floor reached
stopcancel illuminate
open
close
from UML By Examples, http://www.geocities.com/SiliconValley/Network/1582/uml-example.htm
Recommended