lecture 1 uml with java implementation

186
Please find your perfect seat first 3 rows, you will sit there this June! tlc2 / Ewe2010! www.uh.edu/webct psid / mmddyya! COSC 1320 Please find your perfect seat first 3 rows, you will sit there this June! Please find your perfect seat first 3 rows, you will sit there this June!

Upload: thewumberlog

Post on 12-Nov-2014

3.135 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Lecture 1 uml with java implementation

Please find your perfect seat first 3 rows,

you will sit there this June!

tlc2 / Ewe2010!

www.uh.edu/webct

psid / mmddyya!

COSC 1320

Please find your perfect seat first 3 rows,

you will sit there this June!

Please find your perfect seat first 3 rows,

you will sit there this June!

Page 2: Lecture 1 uml with java implementation

Introduction to Computer Science

IICOSC 1320/6305

Lecture 1: Software Engineering and Classes

UML, OOA/OOD/JAVA Implementation

A TOP DOWN EXAMPLE

(Chapter 12)

Page 3: Lecture 1 uml with java implementation

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-3

Page 4: Lecture 1 uml with java implementation

Class Participation NetBeans Projects

C. (Out of 40 points.) Candi Machine Start NetBeans 6.9.1

B. (Out of 30 points.) Java Circle Perimeter Start NetBeans 6.9.1

A. (Out of 30 points.) UML Class Diagram

Page 5: Lecture 1 uml with java implementation

Software Engineering• Software Engineering is the study of the techniques and theory

that support the development of high-quality software

• The focus is on controlling the development process to achieve consistently good results

• We want to:• satisfy the client – the person or organization who sponsors the

development

• meet the needs of the user – the people using the software for its intended purpose

Page 6: Lecture 1 uml with java implementation

Goals of Software Engineering• Solve the right problem

• more difficult than it might seem• client interaction is key

• Deliver a solution on time and under budget• there are always trade-offs

• Deliver a high-quality solution• beauty is in the eye of the beholder• we must consider the needs of various stakeholders

Page 7: Lecture 1 uml with java implementation

Aspects of software quality

Page 8: Lecture 1 uml with java implementation

Development Models• A development life cycle defines a process to be followed

during product development

• Many software development models have been introduced

• All of them address the following fundamental issues in one way or another:

• problem analysis (What?)• design (How?)• implementation• evaluation

• maintenance

Page 9: Lecture 1 uml with java implementation

Problem Analysis - What• We must specify the requirements of the software system

Page 10: Lecture 1 uml with java implementation

Problem Analysis - What• We must specify the requirements of the software system

• Must be based on accurate information

• Various techniques:• discussions and negotiations with the client• modeling the problem structure and data flow• observation of client activities• analysis of existing solutions and systems

Page 11: Lecture 1 uml with java implementation

Design - How• We must specify the solution

• You would not consider building a bridge without a design

• Design involves determining:

• the overall software structure (architecture)• the key objects, classes, and their relationships

• Alternatives should be considered

Page 12: Lecture 1 uml with java implementation

Implementation

• We must turn the design into functional software

• Too many people consider this the primary act of software development

• May involve the reuse of existing software components

Page 13: Lecture 1 uml with java implementation

Evaluation

• We must verify that the system conforms to the requirements

• This includes, but goes way beyond, testing code with test cases

• It is possible to build a system that has no bugs and yet is completely wrong

Page 14: Lecture 1 uml with java implementation

Maintenance• After a system is initially developed, it must be

maintained

• This includes:• fixing errors• making enhancements to meet the changing needs of users

• The better the development effort, the easier the maintenance tasks will be

Page 15: Lecture 1 uml with java implementation

The Waterfall Model• One of the earliest development models

• Each stage flows into the next

• Driven by documentation

• Advantages:• Lays out clear milestones and deliverables• Has high visibility – managers and clients can see the

status

• Disadvantages:• late evaluation• not realistic in many situations

Page 16: Lecture 1 uml with java implementation

The Spiral Model• Developed by Barry Boehm in the mid '80s

• Embraces an iterative process, where activities are performed over and over again for different aspects of the system

• Designed to reduce the risks involved• Continually refines the requirements• Each loop through the spiral is a complete phase of development

Page 17: Lecture 1 uml with java implementation

The Evolutionary Model***

• Like the spiral model, an evolutionary approach embraces continual refinement

• Intermediate versions of the system are created for evaluation by both the developers and the client

• May be more difficult to maintain depending on the attention given to the iterations

Page 18: Lecture 1 uml with java implementation

The Unified Modeling Language

• The Unified Modeling Language (UML) has become a standard notation for software analysis (OOA) & design (OOD)

• It is language independent

• It includes various types of diagrams (models) which use specific icons and notations

• However, it is flexible – the details you include in a given diagram depend on what you are trying to capture and communicate

Page 19: Lecture 1 uml with java implementation

UML Class Diagrams• UML class diagrams may include:

• The classes used in the system• The static relationships among classes• The attributes and operations of each class• The constraints on the connections among objects

• An attribute is class level data, including variables and constants

• An operation is essentially equivalent to a method

• May include visibility details

+ public- private# protected

Page 20: Lecture 1 uml with java implementation

UML class diagram showing inheritance relationships

Page 21: Lecture 1 uml with java implementation

UML class diagram showing an association

Page 22: Lecture 1 uml with java implementation

One class shown as an aggregate of other classes

Page 23: Lecture 1 uml with java implementation

UML diagram showing a class implementing an interface

Page 24: Lecture 1 uml with java implementation

One class indicating its use of another

Page 25: Lecture 1 uml with java implementation

Objectives

• Advise on the class

• Software Engineering

• Problem solving

• Memory

• Classes

Page 26: Lecture 1 uml with java implementation

Life Cycle

“Read a sequence of marks from the user, ending with the word ‘done’ and then print the average of the marks.”

Page 27: Lecture 1 uml with java implementation

Specify — Design — Code — Test

Edit—Compile—Run cycle:

Problem Solving

InitialDesign

Edit:typing in the Java code

Compile:Translating to executable

instructions

Run:Testing the program to

see that it works

Specification

Page 28: Lecture 1 uml with java implementation

Life Cycle

Problem

⇒ Specification

⇒ Design of Solution

⇒ Computer program

⇒ Test and debug!

“Find the average mark in an exam”

“Read a sequence of marks from the user, ending with the word ‘done’ and then print the average of the marks.”

Page 29: Lecture 1 uml with java implementation

Life Cycle

Problem

⇒ Problem description

⇒ Design of Solution

⇒ Computer program

⇒ Test and debug

“Initialise count and sum loop:

Prompt user for next numberif user enters a non-number, then exit loopread the number, and add to the sumincrement the count

end loop print out the value of sum/count”

pseudocode

Page 30: Lecture 1 uml with java implementation

Life Cycle ⇒ Problem description

⇒ Design of Solution ⇒ Computer program

⇒ Test and debug

import java.util.*;public class ExamAverage {

public void findAverage () {

int count = 0;double sum = 0;Scanner input = new Scanner(System.in); while (true){

System.out.print("Enter next mark: ");if ( ! input.hasNextDouble() ) break;sum = sum + input.nextDouble();count = count + 1;

}System.out.printf(“average mark = %4.2f\n", sum/count);

}}

Page 31: Lecture 1 uml with java implementation

Life Cycle

⇒ Problem description

⇒ Design of Solution

⇒ Computer program

⇒ Test and debug:Run the program on a range of possible inputs and check that it is correct.

Enter next mark: 70

Enter next mark: 85

Enter next mark: 65

Enter next mark: done

average mark = 73.33

Enter next mark: done

Error: divide by zero

Page 32: Lecture 1 uml with java implementation

Objectives

• Advise on the class

• Software Engineering

• Problem solving

• Memory

• Classes

Page 33: Lecture 1 uml with java implementation

Machine Languages, Assembly Languages, and High-level Languages

• Three types of programming languages1. Machine languages

• Strings of numbers giving machine specific instructions• Example:

+1300042774+1400593419+1200274027

2. Assembly languages• English-like abbreviations representing elementary computer operations (translated via

assemblers)• Example:

LOAD BASEPAYADD OVERPAYSTORE GROSSPAY

3. High-level languages• Codes similar to everyday English• Use mathematical notations (translated via compilers)• Example:

grossPay = basePay + overTimePay

Page 34: Lecture 1 uml with java implementation

History of C

• C • Evolved by Ritchie from two previous programming languages,

BCPL and B• Used to develop UNIX• Used to write modern operating systems• Hardware independent (portable)• By late 1970's C had evolved to "Traditional C“

• Standardization• Many slight variations of C existed, and were incompatible• Committee formed to create a "unambiguous, machine-

independent" definition• Standard created in 1989, updated in 1999

Page 35: Lecture 1 uml with java implementation

The C Standard Library

• C programs consist of pieces/modules called functions

• A programmer can create his own functions• Advantage: the programmer knows exactly how it works• Disadvantage: time consuming

• Programmers will often use the C library functions• Use these as building blocks

• Avoid re-inventing the wheel!• If a premade function exists, generally best to use it rather than

rewrite • Library functions carefully written, efficient, and portable

Page 36: Lecture 1 uml with java implementation

The Key Software Trend: Object Technology• Objects

• Reusable software components that model items in the real world

• Meaningful software units• Date objects, time objects, paycheck objects, invoice

objects, audio objects, video objects, file objects, record objects, etc.

• Any noun can be represented as an object!

• More understandable, better organized, and easier to maintain than procedural programming

• Favor modularity

Page 37: Lecture 1 uml with java implementation

C++

• C++

• Superset of C developed by Bjarne Stroustrup at Bell Labs

• "Spruces up" C, and provides object-oriented capabilities

• Object-oriented very powerful• 10 to 100 fold increase in productivity

• Dominant language in industry and academia

Page 38: Lecture 1 uml with java implementation

Java

• Java is used to

• Create Web pages with dynamic and interactive content

• Develop large-scale enterprise applications

• Enhance the functionality of Web servers

• Provide applications for consumer devices (such as cell phones, pagers and personal digital assistants)

Page 39: Lecture 1 uml with java implementation

Other High-level Languages

• Other high-level languages

• FORTRAN • Used for scientific and engineering applications

• COBOL • Used to manipulate large amounts of data

• Pascal • Intended for academic use

Page 40: Lecture 1 uml with java implementation

Basics of a Typical C Program Development Environment

Phases of C++ Programs:

1. Edit

2. Preprocess

3. Compile

4. Link

5. Load

6. Execute

Program is created inthe editor and storedon disk.

Preprocessor programprocesses the code.

Loader puts program in memory.

CPU takes eachinstruction and executes it, possibly storing new data values as the program executes.

Compiler creates object code and storesit on disk.

Linker links the objectcode with the libraries

Loader

Primary Memory

Compiler

Editor

Preprocessor

Linker

 

Primary Memory

.

.

.

.

.

.

.

.

.

.

.

.

Disk

Disk

Disk

CPU

Disk

Disk

Page 41: Lecture 1 uml with java implementation

Memory Concepts

• Variable names

• Correspond to actual locations in computer's memory

• Every variable has name, type, size and value

• When new value placed into variable, overwrites previous value

• Reading variables from memory nondestructive

Page 42: Lecture 1 uml with java implementation

Memory Concepts

std::cin >> integer1;Assume user entered 45

std::cin >> integer2;Assume user entered 72

sum = integer1 + integer2;

integer1 45

integer1 45

integer2 72

integer1 45

integer2 72

sum 117

Page 43: Lecture 1 uml with java implementation

Memory

Main memory is divided into many memory locations (or cells)

927892799280928192829283928492859286

Each memory cell has a numeric address, which uniquely identifies it

Page 44: Lecture 1 uml with java implementation

Storing Information

927892799280928192829283928492859286

Large values arestored in consecutivememory locations

10011010Each memory cell stores a set number of bits (usually 8 bits, or one byte)

Page 45: Lecture 1 uml with java implementation

References• Note that a primitive variable contains the value itself, but an object

variable contains the address of the object

• An object reference can be thought of as a pointer to the location of the object

• Rather than dealing with arbitrary addresses, we often depict a reference graphically

"Steve Jobs"name1

num1 38

Page 46: Lecture 1 uml with java implementation

Assignment Revisited

• The act of assignment = takes a copy of a value and stores it in a variable

• For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Page 47: Lecture 1 uml with java implementation

Reference Assignment

• For object references, assignment copies the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Page 48: Lecture 1 uml with java implementation

Numeric Primitive Data• The difference between the various numeric primitive

types is their size, and therefore the values they can store:Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038

+/- 1.7 x 10308

Max Value

12732,7672,147,483,647> 9 x 1018

927892799280928192829283928492859286

Page 49: Lecture 1 uml with java implementation

C/C++ Program

1

2

3

4

5

6

7

8

Page 50: Lecture 1 uml with java implementation

Another Picture

Page 51: Lecture 1 uml with java implementation

Assembly & Machine Language

Page 52: Lecture 1 uml with java implementation

An Assembler

Page 53: Lecture 1 uml with java implementation

Compiler

Page 54: Lecture 1 uml with java implementation

Software: User Programs

• Programs that are neither OS programs nor applications are called user programs.

• User programs are what you’ll be writing in this course.

Page 55: Lecture 1 uml with java implementation

Putting it all togetherPrograms and applications that are not running are stored

on disk.

RAM DiskCPUCache

Bus

OS App

Page 56: Lecture 1 uml with java implementation

Putting it all together

When you launch a program, the OS controls the CPU and loads the program from disk to RAM.

RAM DiskCPUCache

Bus

OS AppA

ppOS

Page 57: Lecture 1 uml with java implementation

Putting it all together

The OS then relinquishes the CPU to the program, which begins to run.

RAM DiskCPUCache

Bus

OS AppA

ppApp

Page 58: Lecture 1 uml with java implementation

The Fetch-Execute Cycle

As the program runs, it repeatedly fetches the next instruction (from memory/cache), executes it, and stores any results back to memory.

RAM DiskCPUCache

Bus

OS AppAppA

pp

That’s all a computer does: fetch-execute-store, millions of times each second!

Page 59: Lecture 1 uml with java implementation

Object Oriented Paradigm

Page 60: Lecture 1 uml with java implementation

Overview

Understand Classes and Objects.

Understand some of the key concepts/features in the Object Oriented paradigm.

Benefits of Object Oriented paradigm.

Page 61: Lecture 1 uml with java implementation

OOP: Model, map, Reuse, extend

Model the real world problem to user’s perceive

Use similar metaphor in computational env.

Construct Reusable components

Create new components from existing ones.

Page 62: Lecture 1 uml with java implementation

Examples of Objects

Figure 1.9: Examples of objects

CAR

VDU

BOY GIRL

TREEBOOK

CLOCK

TRIANGLE

Page 63: Lecture 1 uml with java implementation

Classes : Objects with the same attributes and behavior

Person Objects

Vehicle Objects

Polygon Objects

Abstract Person ClassAttributes:Operations:

Name, Age, SexSpeak(), Listen(), Walk()

Into

Abstract Vehicle ClassAttributes:Operations:

Name, Model, ColorStart(), Stop(), Accelerate()

Into

AbstractPolygon ClassAttributes:

Operations: Draw(), Erase(), Move()

Vertices, Border,Color, FillColorInto

Figure 1.12: Objects and classes

Page 64: Lecture 1 uml with java implementation

Object Oriented Paradigm: Features

OOP Paradigm

Encapsulation

Multiple Inheritance

Genericity

Delegation

Persistence

Polymorphism

Single Inheritance

Data Abstraction

Page 65: Lecture 1 uml with java implementation

Java’s OO Features

OOP Paradigm

Encapsulation

Multiple Inheritance

Genericity

Delegation

Persistence

Polymorphism

Single Inheritance

Data Abstraction

Java

Page 66: Lecture 1 uml with java implementation

Encapsulation Associates the Code &

the Data it manipulates into a single unit; and keeps them safe from external interference and misuse.OOP

Paradigm

Encapsulation

Multiple Inheritance

Genericity

Delegation

Persistence

Polymorphism

Single Inheritance

Data Abstraction

Data

Code

Page 67: Lecture 1 uml with java implementation

Data Abstraction The technique of creating

new data types that are well suited to an application.

It allows the creation of user defined data types, having the properties of built data types and a set of permitted operators.

In Java, partial support. In C++, fully supported

(e.g., operator overloading).

OOP Paradigm

Encapsulation

Multiple Inheritance

Genericity

Delegation

Persistence

Polymorphism

Single Inheritance

Data Abstraction

Page 68: Lecture 1 uml with java implementation

Abstract Data Type (ADT)

A structure that contains both data and the actions to be performed on that data.

Class is an implementation of an Abstract Data Type.

Page 69: Lecture 1 uml with java implementation

Class Definition Syntax

69

Page 70: Lecture 1 uml with java implementation

Class - Example

class Account {

private String accountName;private double accountBalance;

public withdraw();public deposit();public determineBalance();

} // Class Account

Page 71: Lecture 1 uml with java implementation

Class

Class is a set of attributes and operations that are performed on the attributes.

Account

accountNameaccountBalance

withdraw()deposit()determineBalance()

Student

nameagestudentId

getName()getId()

Circle

centreradius

area()circumference()

Page 72: Lecture 1 uml with java implementation

Objects

An Object Oriented system is a collection of interacting Objects.

Object is an instance of a class.

Page 73: Lecture 1 uml with java implementation

Classes /Objects

Student:John

:Jill

John and Jill are objects of class

Student

Circle:circleA

:circleB

circleA and circleB are

objects of classCircle

Page 74: Lecture 1 uml with java implementation

Class

A class represents a template for several objects that have common properties.

A class defines all the properties common to the object - attributes and methods.

A class is sometimes called the object’s type.

Page 75: Lecture 1 uml with java implementation

Object Objects have state and classes don’t.

John is an object (instance) of class Student. name = “John”, age = 20, studentId = 1236

Jill is an object (instance) of class Student. name = “Jill”, age = 22, studentId = 2345

circleA is an object (instance) of class Circle. centre = (20,10), radius = 25

circleB is an object (instance) of class Circle. centre = (0,0), radius = 10

Page 76: Lecture 1 uml with java implementation

Encapsulation All information (attributes and methods) in an

object oriented system are stored within the object/class.

Information can be manipulated through operations performed on the object/class – interface to the class. Implementation is hidden from the user.

Object support Information Hiding – some attributes and methods can be hidden from the user.

Page 77: Lecture 1 uml with java implementation

Encapsulation - Example

class Account { private double accountBalance;

public withdraw();public deposit();public determineBalance();

} // Class Account

depositwithdraw

determine Balance

accountBalance

message

message

message

Page 78: Lecture 1 uml with java implementation

Data Abstraction

The technique of creating new data types that are well suited to an application.

It allows the creation of user defined data types, having the properties of built in data types and more.

Page 79: Lecture 1 uml with java implementation

Abstraction - Example

class Account { private String accountName;private double accountBalance;

public withdraw();public deposit();public determineBalance();

} // Class Account

Creates a data type Account

Account acctX;

Page 80: Lecture 1 uml with java implementation

Inheritance New data types (classes)

can be defined as extensions to previously defined types.

Parent Class (Super Class) – Child Class (Sub Class)

Subclass inherits properties from the parent class.

Parent

Child

Inheritedcapability

Page 81: Lecture 1 uml with java implementation

Inheritance - Example Examples

Define Person to be a class A Person has attributes, such as age, height, gender Assign values to attributes when describing object

Define student to be a subclass of Person A student has all attributes of Person, plus attributes of

his/her own ( student no, course_enrolled) A student has all attributes of Person, plus attributes of

his/her own (student no, course_enrolled) A student inherits all attributes of Person

Define lecturer to be a subclass of Person lecturer has all attributes of Person, plus attributes of

his/her own ( staff_id, subjectID1, subjectID2)

Page 82: Lecture 1 uml with java implementation

Inheritance - Example

Circle Class can be a subclass (inherited from) of a parent class - Shape

Shape

Circle Rectangle

Page 83: Lecture 1 uml with java implementation

Inheritance - Example Inheritance can also have multiple levels.

Shape

Circle Rectangle

GraphicCircle

Page 84: Lecture 1 uml with java implementation

Uses of Inheritance - Reuse

If multiple classes have common attributes/methods, these methods can be moved to a common class - parent class.

This allows reuse since the implementation is not repeated.

Example : Rectangle and Circle method have a common method move(), which requires changing the center coordinate.

Page 85: Lecture 1 uml with java implementation

move(newCentre){ centre = newCentre;

}

Uses of Inheritance - Reuse

Circle

centreradiusarea()

circumference()move(newCentre)

Rectangle

centreheightwidtharea()

circumference()move(newCentre)

move(newCentre){ centre = newCentre;}

move(newCentre){ centre = newCentre;}

Page 86: Lecture 1 uml with java implementation

86

Uses of Inheritance - Reuse

Shape

centre

area()circumference()move(newCentre)

Rectangle

heightwidth

area()circumference()

Circle

radius

area()circumference()

move(newCentre){ centre = newCentre}

Page 87: Lecture 1 uml with java implementation

Uses of Inheritance - Specialization

Specialized behavior can be added to the child class.

In this case the behaviour will be implemented in the child class.

e.g. the implementation of area() method in the Circle class is different from the area() method in the Rectangle class.

area() method in the child classes override the method in parent classes().

Page 88: Lecture 1 uml with java implementation

88

Uses of Inheritance - Specialization

area(){ return height*width;}

Circle

centreradiusarea()

circumference()move(newCentre)

Rectangle

centreheightwidtharea()

circumference()move(newCentre)

area(){ return pi*r^2;}

Page 89: Lecture 1 uml with java implementation

89

Uses of Inheritance - Specialization

Shape

centre

area()circumference()move(newCentre)

Rectangle

heightwidth

area()circumference()

Circle

radius

area()circumference()

area(); - not implemented and left for the child classes to implement

area(){ return pi*r^2;}

area(){ return height*width;}

Page 90: Lecture 1 uml with java implementation

Uses of Inheritance – Common Interface

All the operations that are supported for Rectangle and Circle are the same.

Some methods have common implementation and others don’t.

move() operation is common to classes and can be implemented in parent.

circumference(), area() operations are significantly different and have to be implemented in the respective classes.

The Shape class provides a common interface where all 3 operations move(), circumference() and area().

Page 91: Lecture 1 uml with java implementation

Uses of Inheritance - Extension

Extend functionality of a class. Child class adds new operations to the

parent class but does not change the inherited behavior.

e.g. Rectangle class might have a special operation that may not be meaningful to the Circle class - rotate90degrees()

Page 92: Lecture 1 uml with java implementation

Uses of Inheritance - Extension

Shape

centre

area()circumference()move(newCentre)

Rectangle

heightwidth

area()circumference()rotate90degrees()

Circle

radius

area()circumference()

Page 93: Lecture 1 uml with java implementation

Uses of Inheritance – Multiple Inheritance

Inherit properties from more than one class.

This is called Multiple Inheritance.

Shape

Circle

Graphics

Page 94: Lecture 1 uml with java implementation

Uses of Multiple Inheritance

This is required when a class has to inherit behavior from multiple classes.

In the example Circle class can inherit move() operation from the Shape class and the paint() operation from the Graphics class.

Multiple inheritance is not supported in JAVA but is supported in C++.

Page 95: Lecture 1 uml with java implementation

Uses of Inheritance – Multiple Inheritance

Shape

centre

area()circumference()move(newCentre)

Circle

radius

area()circumference()

GraphicCircle

color

paint()

Page 96: Lecture 1 uml with java implementation

Polymorphism

Polymorphic which means “many forms” has Greek roots. Poly – many Morphos - forms.

In OO paradigm polymorphism has many forms.

Allow a single object, method, operator associated with different meaning depending on the type of data passed to it.

Page 97: Lecture 1 uml with java implementation

Polymorphism An object of type Circle or Rectangle can be

assigned to a Shape object. The behavior of the object will depend on the object passed.

circleA = new Circle(); Create a new circle object

Shape shape = circleA;shape.area(); area() method for circle class will be executed

rectangleA = new Rectangle(); Create a new rectangle object shape= rectangleA;shape.area() area() method for rectangle will be

executed.

Page 98: Lecture 1 uml with java implementation

Polymorphism – Method Overloading

Multiple methods can be defined with the same name, different input arguments.

Method 1 - initialize(int a)Method 2 - initialize(int a, int b)

Appropriate method will be called based on the input arguments.

initialize(2) Method 1 will be called.initialize(2,4) Method 2 will be called.

Page 99: Lecture 1 uml with java implementation

99

Polymorphism – Operator Overloading

Allows regular operators such as +, -, *, / to have different meanings based on the type.

e.g. + operator for Circle can re-definedCircle c = c + 2;

Not supported in JAVA. C++ supports it.

Page 100: Lecture 1 uml with java implementation

100

Persistence

The phenomenon where the object outlives the program execution.

Databases support this feature.

In Java, this can be supported if users explicitly build object persistency using IO streams.

Page 101: Lecture 1 uml with java implementation

101

Why OOP? Greater Reliability

Break complex software projects into small, self-contained, and modular objects

Maintainability Modular objects make locating bugs easier,

with less impact on the overall project

Greater Productivity through Reuse!

Faster Design and Modelling

Page 102: Lecture 1 uml with java implementation

Benefits of OOP.. Inheritance: Elimination of Redundant

Code and extend the use of existing classes.

Build programs from existing working modules, rather than having to start from scratch. save development time and get higher productivity.

Encapsulation: Helps in building secure programs.

Page 103: Lecture 1 uml with java implementation

Benefits of OOP.. Multiple objects to coexist without any

interference.

Easy to map objects in problem domain to those objects in the program.

It is easy to partition the work in a project based on objects.

Page 104: Lecture 1 uml with java implementation

Benefits of OOP..

Object Oriented Systems can be easily upgraded from small to large systems.

Message-Passing technique for communication between objects make the interface descriptions with external systems much simpler.

Software complexity can be easily managed.

Page 105: Lecture 1 uml with java implementation

Summary Object Oriented Analysis, Design, and Programming

is a Powerful paradigm

Enables Easy Mapping of Real world Objects to Objects in the Program

This is enabled by OO features: Encapsulation Data Abstraction Inheritance Polymorphism Persistence

Standard OO Analysis and Design (UML) and Programming Languages (C++/Java) are readily accessible.

Page 106: Lecture 1 uml with java implementation

What We Will Learn?¨ How to solve a problem.

¨ Using Java ¨ Java is a good language to start doing object oriented (OO) in because it attempts to stay true to all the different OO paradigms.

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.

Page 107: Lecture 1 uml with java implementation

Differences Between Procedural Programming (PP) and Object Oriented Programming (OOP)

¨ The focus of procedural programming is to break down a programming task into a collection of variables, functions and modules,

¨ whereas in object oriented programming it is to break down a programming task into objects with each "object" encapsulating its own data (variables) and methods (functions).

¨ We will sometimes use predefined classes and sometimes write our own classes.

Variables

Functions

Data

Methods

Class

PP OOP

Page 108: Lecture 1 uml with java implementation

Example programDesign and Implement a program to calculate perimeter of a circle.

¨ PP¨ C

¨ OOP¨ Java

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-108CLASS Participation A!

Page 109: Lecture 1 uml with java implementation

Example program, PP in C Design and Implement

#include <iostream>

const double PI=3.14;

void main(){

double circleRadius = 10;double circlePerimeter = 2*PI*circleRadius;

printf("Circle Perimiter %f \n",circlePerimeter);

system("pause");}

Driver.c

CLASS Participation B!

Variables

Functions

PP

Page 110: Lecture 1 uml with java implementation

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-110CLASS Participation B!

Page 111: Lecture 1 uml with java implementation

Example program, OOP in Java

7-111

public class Circle{ private double radius; static double PI = 3.14;

public Circle(double r) { radius = r; }

double getPerimeter() { return 2 * PI * radius; }}

Circle.java

public class Main {

public static void main(String[] args) { Circle circle = new Circle(10); System.out.println("Circle Perimeter " + circle.getPerimeter()); }}

Main.java

¨ The core of OOP: “Put related things together.”

CLASS Participation B!

Design

Data

Methods

OOP

Implement

Page 112: Lecture 1 uml with java implementation

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-112

Page 113: Lecture 1 uml with java implementation

Example program, PP in C Design and Implement

#include <iostream>

const double PI=3.14;

void main(){

double circleRadius = 10;double circlePerimeter = 2*PI*circleRadius;

printf("Circle Perimiter %f \n",circlePerimeter);

system("pause");}

Driver.c

CLASS Participation B!

Variables

Functions

PP

Page 114: Lecture 1 uml with java implementation

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-114CLASS Participation B!

Page 115: Lecture 1 uml with java implementation

Start with OOA&OOD or Coding?¨ The heart of object-oriented problem solving is the construction of a model.¨ Architects design buildings. Builders use the designs to create buildings.

Blueprints are the standard graphical language that both architects and builders must learn as part of their trade.

¨ Writing software is not unlike constructing a building. ¨ Writing software begins with the construction of a model. A model is an

abstraction of the underlying problem. ¨ Unified Modeling Language (UML) is a pictorial language used to make software

blueprints.

“A picture is worth a thousand words”

Page 116: Lecture 1 uml with java implementation

OO Analysis & Design: UML¨ Unified Modeling Language (UML) is a standardized general purpose

modeling language in the field of software engineering.

¨ UML includes a set of graphical notation techniques to create visual models of software intensive systems.

¨ UML is not a programming language but tools can be used to generate code in various languages using UML diagrams.

¨ UML has a direct relation with object oriented analysis and design.

¨ The most important purpose of object oriented (OO) analysis is to identify objects of a system to be designed.

¨ After identifying the objects their relationships are identified and finally the design is produced.

Page 117: Lecture 1 uml with java implementation

Unified Modeling Language

¨ UML provides structure for problem solving.¨ A method for modeling object oriented programs.

¨ A means for visualizing, constructing and documenting software projects.¨ Promotes component reusability.

¨ You will not understand what your algorithm does two weeks after you wrote it. But if you have the model, you will catch up fast and easily.

¨ Teamwork for parallel development of large systems.¨ UML includes 13 diagrams.

Page 118: Lecture 1 uml with java implementation

1. UML Use Case Diagrams

¨ The use case diagram is the first model when starting a project. ¨ A use case is a set of scenarios that describing an interaction between a user and a

system. The emphasis is on what a system does rather than how.¨ Use Case Diagram displays the relationship among actors (users) and use cases

(scenarios ).¨ Use cases are used during the analysis phase of a project to identify and

to partition system functionality. The two main components of a use case diagram are use cases and actors.

¨ An actor is represents a user or another system that will interact with the system you are modeling.

¨ Use cases describe the behavior of the system when one of these actors perform a task.

Page 119: Lecture 1 uml with java implementation

1. UML Use Case Diagrams

¨ We first write use cases, and then we draw them.

¨ For example, here is a typical use case for a point of sale system. Here is just ONE USE CASE from this system

¨ 1. Cashier swipes product over scanner, scanner reads UPC code.

2. Price and description of item, as well as current subtotal appear on the display facing the customer. The price and description also appear on the cashier’s screen.

3. Price and description are printed on receipt.

4. System emits an audible “acknowledgement” tone to tell the cashier that the UPC code was correctly read.

¨ Clearly a point of sale system has many more use cases than this.

Use Case 1: Check Out Item

Page 120: Lecture 1 uml with java implementation

1. Use Case Diagrams¨ Drawing Use Case Diagrams

1. Cashier swipes product over scanner, scanner reads UPC code.2. Price and description of item, as well as current subtotal appear on the display facing the customer. The price and

description also appear on the cashier’s screen.3. Price and description are printed on receipt.4. System emits an audible “acknowledgement” tone to tell the cashier that the UPC code was correctly read.

¨ Inside the boundary rectangle we see the use cases. These are the ovals with names inside. The lines connect the actors to the use cases that they stimulate.

Use Case 1

Use Case 2

Use Case 3

Use Case 4

Use Case 1: Check Out Item

Page 121: Lecture 1 uml with java implementation

2. UML Class Diagrams¨ The purpose of a class diagram is to depict the classes within a model.¨ A class diagram gives an overview of a system by showing its classes and the

relationships among them. ¨ In an object oriented application, classes have attributes (member variables),

operations (member methods/functions) and relationships with other classes.¨ The fundamental element of the class diagram is an icon the represents a class. A

class icon is simply a rectangle divided into 3 compartments. ¨ The topmost compartment contains the name of the class. The middle

compartment contains a list of attributes (member variables), and the bottom compartment contains a list of operations (member methods/functions).

¨ In many diagrams, the bottom two compartments are omitted. Even when they are present, they typically do not show every attribute and operations. The goal is to show only those attributes and operations that are useful for the particular diagram.

¨ The central class is the Order. Associated with it are the Customer making the purchase and the Payment. A Payment is one of three kinds: Cash, Check, or Credit. The order contains OrderDetails (line items), each with its associated Item.

Page 122: Lecture 1 uml with java implementation

2. UML Class Diagrams

¨ Notice that each member variable is followed by a colon and by the type of the variable.

¨ Notice also that the return values follow the member methods/functions in a similar fashion.

¨ Finally, notice that the member function arguments are just types.

¨ Again, these can be omitted if they are redundant...

Page 123: Lecture 1 uml with java implementation

2. UML Class Diagrams¨ Class diagrams also display relationships among classes . ¨ Each instance of type Circle seems to contain an

instance of type Point.¨ This is a relationship known as composition.¨ It can be depicted in UML using a class relationship.

¨ The black diamond represents composition. ¨ It is placed on the Circle class because it is the Circle that is composed of a Point.¨ The arrowhead on the other end of the relationship denotes that the relationship is

navigable in only one direction. That is, Point does not know about Circle. But, Circle knows about Point. The arrow lets you know who "owns" the association's implementation.¨ At the code level, this implies a NO import Circle.java within Point.java ¨ BUT, this also implies a import Point.java within Circle.java

¨ In UML relationships are presumed to be bidirectional unless the arrowhead is present to restrict them.

Page 124: Lecture 1 uml with java implementation

2. UML Class Diagrams

¨ Composition relationships (black diamond) are a strong form of aggregation.¨ Aggregation is a whole/part relationship. In this case, Circle is the whole, and Point is

part of Circle .¨ Composition also indicates that the lifetime of Point is dependent upon Circle. This

means that if Circle is destroyed, Point will be destroyed with it.

¨ In this case we have represented the composition relationship as a member variable.

Page 125: Lecture 1 uml with java implementation

2. UML Class Diagrams

¨ The weak form of aggregation is denoted with an open diamond.¨ This relationship denotes that the aggregate class (the class with the white diamond

touching it) is in some way the “whole”, and the other class in the relationship is somehow “part” of that whole.

¨ Window class contains many Shape instances.¨ In UML the ends of a relationship are referred to as its “roles”.¨ Notice that the role at the Shape end of the aggregation is marked with a “*”

(multiplicity). Multiplicity denotes the number of objects that can participate in the relationship.

¨ Notice also that the role has been named. This is the name of the instance variable within Window that holds all the Shapes.

Page 126: Lecture 1 uml with java implementation

2. UML Class Diagrams¨ Another common relationship in class diagrams is a generalization. A generalization

is used when two classes are similar, but have some differences. In other words, it shows the inheritance relationship .

¨ The inheritance relationship (generalization) in UML is depicted by a peculiar triangular arrowhead.

¨ In this diagram we see that Circle and Square (derived classes) both derive from Shape (base class/super class).

¨ Circle and Square(derived classes) have some similarities, but each class has some of its own attributes and operations.

Page 127: Lecture 1 uml with java implementation

Candy Machine Case Study

Requirements

Textual AnalysisUML Modeling

Page 128: Lecture 1 uml with java implementation

UML Class DiagramSimplified methodology

1. Write down detailed description of problem

2. Identify all (relevant) nouns and verbs

3. From list of nouns, select objects

4. Identify data components of each object

5. From list of verbs, select operations

Page 129: Lecture 1 uml with java implementation

A place to buy candy is from a candy machine. The candy machine has four dispensers to hold and release items sold by the candy machine as well as a cash register. The machine sells four products— candies, chips, gum, and cookies— each stored in a separate dispenser.

UML Class Diagram

The program should do the following: Show the customer the different products sold by the candy

machine Let the customer make the selection Show the customer the cost of the item selected Accept money from the customer Return change Release the item; that is, make the sale textual analysis

Page 130: Lecture 1 uml with java implementation

UML Class DiagramTextual Analysis

Place, candy, candy machine, cafeteria, dispenser, items, cash register, chips, gum, cookies, customer, products, cost ( of the item), money, and change.In this description of the problem, products stand for items such as candy, chips, gum, and cookies. In fact, the actual product in the machine is not that important. What is important is to note that there are four dispensers, each capable of dispensing one product. Further, there is one cash register. Thus, the candy machine consists of four dispensers and one cash register. Graphically, this can be represented as in Figure 6-14.

Page 131: Lecture 1 uml with java implementation

UML Class Diagram

Page 132: Lecture 1 uml with java implementation

You can see that the program you are about to write is supposed to deal with dispensers and cash registers. That is, the main objects are four dispensers and a cash register.

Because all the dispensers are of the same type, you need to create a class, say, Dispenser, to create the dispensers.

Similarly, you need to create a class, say, CashRegister, to create a cash register.

We will create the class CandyMachine containing the four dispensers, a cash register, and the application program.

UML Class DiagramTextual Analysis

Page 133: Lecture 1 uml with java implementation

Dispenser To make the sale, at least one item must be in the dispenser and the customer must know the cost of the product. Therefore, the data members of a dispenser are:

� Product cost

� Number of items in the dispenser

Cash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call

� cashOnHand

Candy Machine The class CandyMachine has four dispensers and a cash register. You can name the four dispensers by the items they store. Therefore, the candy machine has five data members— four dispensers and a cash register.

UML Class DiagramTextual Analysis

Page 134: Lecture 1 uml with java implementation

UML Class DiagramDispenser To make the sale, at least one item must be in the dispenser and the customer must know the cost of the product. Therefore, the data members of a dispenser are:

� Product cost

� Number of items in the dispenser

Page 135: Lecture 1 uml with java implementation

UML Class Diagram

Cash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call

� cashOnHand

Page 136: Lecture 1 uml with java implementation

UML Class Diagram

Candy Machine The class CandyMachine has four dispensers and a cash register. You can name the four dispensers by the items they store. Therefore, the candy machine has five data members—

� four dispensers

� candy,

� chips,

� gum,

� cookies and a

� cash register.

Page 137: Lecture 1 uml with java implementation

UML Class Diagram

The relevant verbs are show ( selection), make ( selection), show ( cost), accept ( money), return ( change), and make ( sale).

The verbs show ( selection) and make ( selection) relate to the candy machine.

The verbs show ( cost) and make ( sale) relate to the dispenser.

Similarly, the verbs accept ( money) and return ( change) relate to the cash register.

Page 138: Lecture 1 uml with java implementation

UML Class Diagram

The verbs show ( selection) and make ( selection) relate to the candy machine.

Thus, the two possible operations are:

� showSelection: Show the number of products sold by the candy machine.

� makeSelection: Allow the customer to select the product.

Page 139: Lecture 1 uml with java implementation

UML Class Diagram

The verbs show ( cost) and make ( sale) relate to the dispenser.

The verb show ( cost) applies to either printing or retrieving the value of the data member cost. The verb make ( sale) applies to reducing the number of items in the dispenser by 1.

Of course, the dispenser has to be nonempty. You must also provide an operation to set the cost and the number of items in the dispenser.

Thus, the operations for a dispenser object are:

� getCount: Retrieve the number of items in the dispenser.

� getProductCost: Retrieve the cost of the item.

� makeSale: Reduce the number of items in the dispenser by 1.

� setProductCost: Set the cost of the product.

� setNumberOfItems: Set the number of items in the dispenser

Page 140: Lecture 1 uml with java implementation

UML Class Diagram

Similarly, the verbs accept ( money) and return ( change) relate to the cash register.

The verb accept ( money) applies to updating the money in the cash register by adding the money deposited by the customer. Similarly, the verb return ( change) applies to reducing the money in the cash register by returning the overpaid amount ( by the customer) to the customer.

You also need to ( initially) set the money in the cash register and retrieve the money from the cash register.

Thus, the possible operations on a cash register are: � acceptAmount: Update the amount in the cash register.

� returnChange: Return the change.

� getCashOnHand: Retrieve the amount in the cash register.

� setCashOnHand: Set the amount in the cash register.

Page 141: Lecture 1 uml with java implementation

UML Class Diagram

Page 142: Lecture 1 uml with java implementation

• Show the selection to the customer• Get selection• If selection is valid and the dispenser

corresponding to the selection is not empty, sell the product

UML Class DiagramDetailed Design Pseudocode for showSelection

method

Page 143: Lecture 1 uml with java implementation

• If the dispenser is nonempty:– Prompt customer to enter the item cost– Get the amount entered by the customer– If the amount entered by the customer is less than the cost of the product

• Prompt customer to enter additional amount• Calculate total amount entered by the customer

– If amount entered by the customer is at least the cost of the product• Update the amount in the cash register• Sell the product; that is, decrement the number of items in the

dispenser by 1• Display an appropriate message

– If amount entered is less than cost of item• Return the amount

– If the dispenser is empty• Tell the customer that this product is sold out

UML Class DiagramDetailed Design Pseudocode for makeSale method

Page 144: Lecture 1 uml with java implementation

• Declare a variable of type cashRegister• Declare and initialize four objects dispenserType

• For example: – The statement dispenserType chips(100, 65);

creates a dispenser object, chips, to hold chips; the number of items in the dispenser is 100 and the cost of an item is 65 cents

UML Class DiagramDetailed Design Pseudocode for main method

Page 145: Lecture 1 uml with java implementation

• Declare additional variables as necessary• Show menu• Get the selection• While not done (9 exits)

– Sell product (sellProduct)– Show selection (showSelection)– Get selection

UML Class DiagramDetailed Design Pseudocode for main method

Page 146: Lecture 1 uml with java implementation

Case Study: Candy Machine Implementation - JAVA

CLASS Participation C!

Page 147: Lecture 1 uml with java implementation

Case Study: Candy Machine Implementation- JAVA

Page 148: Lecture 1 uml with java implementation

Case Study: Candy Machine Implementation- JAVA

Page 149: Lecture 1 uml with java implementation

JAVA

Page 150: Lecture 1 uml with java implementation

Video Store Case Study

Requirements

Textual Analysis

UML Modeling

Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved. 7-150

Page 151: Lecture 1 uml with java implementation

OO Analysis & OO Design and Implement in JAVA

¨ A video store intends to offer rentals (and sales) of video tapes and disks to the public. The store management is determined to launch its operations with the support of a computer system. The management has already sourced a number of small-business software packages but has decided to develop its own system.

¨ The video store will keep a stock of video tapes, CDs and DVDs. The inventory has already been ordered from one supplier, but more suppliers will be approached in future orders.

¨ All video tapes and disks will be bar-coded so that a scanning machine integrated with the system can support the rentals and returns. The customer membership cards will also be bar-coded.

¨ Existing customers will be able to place reservations on videos to be collected at a specific date. The system must have a flexible search engine to answer customer enquiries, including enquiries about movies that the video store does not stock (but may order them on request).

¨ The central class is the Order. Associated with it are the Customer making the purchase and the Payment. A Payment is one of three kinds: Cash, Check, or Credit. The order contains OrderDetails (line items), each with its associated Item.

Requirements

Page 152: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together with

any additional definitions and specifications.

USE CASES¨ Before a video can be rented out, the system confirms customer’s identity by swiping

over scanner his/her Video Store membership card.

¨ Actors : ???¨ Use Case 1 : ???

Page 153: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together

with any additional definitions and specifications.

USE CASESBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

Page 154: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together

with any additional definitions and specifications.

USE CASESBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : ???Use Case 2 : ???

Page 155: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together

with any additional definitions and specifications.

USE CASESBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : Customer and EmployeeUse Case 2 : Scan Video Medium

Page 156: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together

with any additional definitions and specifications.USE CASES

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : Customer and EmployeeUse Case 2 : Scan Video Medium

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : ???Use Case 3 : ???

Page 157: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

¨ Actor: Whoever or whatever (person, machine etc.) that interacts with a use case.¨ Use case: It represents a complete unit of functionality of value to an actor.¨ Use Case Diagram: It is a visual representation of actors and use cases together

with any additional definitions and specifications.USE CASES

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : Customer and EmployeeUse Case 2 : Scan Video Medium

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to Card

Page 158: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

USE CASESBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : Customer and EmployeeUse Case 2 : Scan Video Medium

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to Card

The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer. Actors : ???Use Case 5 : ???

Page 159: Lecture 1 uml with java implementation

UML Use Case Diagram – Textual Analysis

USE CASESBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Actors : Customer and EmployeeUse Case 1 : Scan Membership Card

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.Actors : Customer and EmployeeUse Case 2 : Scan Video Medium

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to Card

The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer. Actors : Customer and EmployeeUse Case 5 : Print Receipt

Page 160: Lecture 1 uml with java implementation

An Example: UML Use Case Diagram

Page 161: Lecture 1 uml with java implementation
Page 162: Lecture 1 uml with java implementation

UC3: Accept Payment

Page 163: Lecture 1 uml with java implementation

An Example: What is next?¨ Use Case View

¨ Use Case Diagram

¨ Structural View¨ Class Diagram¨ Object Diagram¨ Composite Structure Diagram

¨ Behavioral View¨ Sequence Diagram¨ Communication Diagram¨ State Diagram¨ Activity Diagram¨ Interaction Overview Diagram¨ Timing Diagram

¨ Implementation View¨ Component Diagram¨ Composite Structure Diagram

¨ Environment View¨ Diagram

Page 164: Lecture 1 uml with java implementation

UML Activity Diagram – Textual Analysis

¨ Activity Diagram represents a behavior that is composed of individual elements.¨ The behavior may be a specification of a use case.

¨ Activity Diagram can graphically represent the flow of events of a use case¨ Shows the steps of computation

¨ We need to find actions (steps) in use case flows.

Page 165: Lecture 1 uml with java implementation

Finding actions in use case – Textual Analysis

1. The Employee requests the system to display the rental charge together with basic customer and video details.

2. If the Customer offers cash payment, the Employee handles the cash, confirms to the system that the payment has been received and asks the system to record the payment as made.

3. If the Customer offers debit/credit card payment, the Employee swipes the card and then requests the Customer to type the card’s PIN number, select debit or credit account, and transmit the payment. Once the payment has been confirmed electronically by the card provider, the system records the payment as made .

Action 1: Display transaction details

Action 2: Key in cash amount

Action 3: Confirm transaction

Action 4: Swipe the card

Action 5: Accept card number

Action 6: Select card account

Action 3: Confirm transaction

Page 166: Lecture 1 uml with java implementation

Finding actions in use case – Textual Analysis

4. The Customer’s card does not swipe properly through the scanner. After three unsuccessful attempts, the Employee enters the card number manually.

5. The Customer does not have sufficient cash and does not offer card payment. The Employee asks the system to verify the Customer’s rating (which accounts for the Customer’s history of payments). Depending on the decision, the Employee cancels the transaction (and the use case terminates) or proceeds with partial payment (and the use case continues).

Action 7: Enter card number manually

Action 8: Verify Customer rating;

Action 9: Refuse transaction;

Action 10: Allow rent with no payment;

Action 11: Allow rent with partial payment

Page 167: Lecture 1 uml with java implementation

UML Activity Diagram – Textual Analysis

¨ Activity diagram shows transitions between actions.¨ Transitions can branch and merge

Action 7: Enter card number manually

Action 8: Verify Customer rating;

Action 9: Refuse transaction;

Action 10: Allow rent with no payment;

Action 11: Allow rent with partial payment

Action 1: Display transaction details

Action 2: Key in cash amount

Action 3: Confirm transaction

Action 4: Swipe the card

Action 5: Accept card number

Action 6: Select card account

Action 3: Confirm transaction

Page 168: Lecture 1 uml with java implementation

UML Activity Diagram

A2:

A1: A4: A5:

A6:A7:

A8:

A11: A10:

A9:

A3:

Page 169: Lecture 1 uml with java implementation

An Example: Activity Diagram

Page 170: Lecture 1 uml with java implementation

An Example: What is next?¨ Use Case View

¨ Use Case Diagram

¨ Structural View¨ Class Diagram¨ Object Diagram¨ Composite Structure Diagram

¨ Behavioral View¨ Sequence Diagram¨ Communication Diagram¨ State Diagram¨ Activity Diagram¨ Interaction Overview Diagram¨ Timing Diagram

¨ Implementation View¨ Component Diagram¨ Composite Structure Diagram

¨ Environment View¨ Diagram

Page 171: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Class modeling captures the static view of the system although it also identifies operations that act on data.

¨ Class modeling elements¨ Classes themselves¨ Attributes (data) and operations (methods) of classes¨ Relationships - associations, aggregation and composition, and generalization.

¨ Class diagram is a combined visual representation for class modeling elements.¨ Assignment of use cases to classes¨ FINDING CLASSES is an iterative task as the initial list of candidate classes is likely to

change.¨ Answering a few questions may help to determine whether a CONCEPT in a USE CASE

is a candidate CLASS or not. The questions are following:

¨ Is the concept a container for data?¨ Does it have separate attributes that will take on different

values?¨ Would it have many instance objects?

Page 172: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

Page 173: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

Video,Customer,MembershipCard

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

Page 174: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

Page 175: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

VideoTapeVideoDisk,Customer,Rental

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

Page 176: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

VideoTapeVideoDisk,Customer,Rental

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.

Page 177: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

VideoTapeVideoDisk,Customer,Rental

Customer,Video,Rental,Payment

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.

Page 178: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

VideoTapeVideoDisk,Customer,Rental

Customer,Video,Rental,Payment

Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.

A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.

The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer.

Page 179: Lecture 1 uml with java implementation

UML Class Diagram – Textual Analysis

¨ Classes?

¨ Classes?

¨ Classes?

¨ Classes?

Video,Customer,MembershipCard

VideoTapeVideoDisk,Customer,Rental

Customer,Video,Rental,Payment

Rental,Receipt

Page 180: Lecture 1 uml with java implementation

UML Class Diagram – Textual AnalysisUC 1 Before a video can be rented out, the system

confirms customer’s identity by swiping over scanner his/her video Store membership card.

C1 Video,C2 Customer,C3 MembershipCard

UC 2 A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.

C4 VideoTape,C5 VideoDisk,C2 Customer,C6 Rental

UC 3 Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.

C2 Customer,C1 Video,C6 Rental,C7 Payment

UC 4 The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer.

C6 Rental,C8 Receipt

Page 181: Lecture 1 uml with java implementation

UML Class Diagram

Page 182: Lecture 1 uml with java implementation

UML Class Diagram– Attributes – Textual Analysis

¨ Identifying attributes for each class

¨ Attributes are discovered form user requirements and domain knowledge.

¨ One or more attributes in a class will have unique values across all the instances (objects) of the class. Such attributes are called keys.

Page 183: Lecture 1 uml with java implementation

C2C3

Page 184: Lecture 1 uml with java implementation
Page 185: Lecture 1 uml with java implementation

UML Class Diagram

Page 186: Lecture 1 uml with java implementation

References¨ http://edn.embarcadero.com/article/31863¨ http://atlas.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/¨ http://www.objectmentor.com/resources/articles/umlClassDiagrams.pdf¨ http://www.objectmentor.com/resources/publishedArticles.html¨ http://www.objectmentor.com/resources/articles/usecases.pdf¨ http://www.objectmentor.com/resources/articles/Use_Cases_UFJP.pdf¨ http://www.tutorialspoint.com/uml/uml_overview.htm