Week 4
Week 4
EL
• 100 paisa is one rupee
• Students live in hostels
PT
• Every student is a member of the library
N
• A student can renew his borrowed books
• The Department has many students
1
• A country has a capital city Identify Classes
• A dining philosopher uses a fork & Relations
• A file is an ordinary file or a directory file
Files contain records
EL
•
• A class can have several attributes
PT
• A relation can be association or generalization
• A polygon is composed of an ordered set of points
N
• A programmer uses a computer language on a project
2
Exercise 1: Draw UML Diagrams
Some persons keep animals as pets.
EL
PT
N
3
Exercise 2: Draw UML Diagrams
A company has many employees and undertakes many
projects. Each project is carried out by a team of
EL
employees.
PT
N
4
• Develop UML Class diagram for a software that we need to
develop to manage a library.
Exercise
• Each library member has a name, date of birth, address, phone
number and email
• Each journal has a name, ISBN code, research areas, shelf in
EL
which located, and an editor. Each editor has a name and a
nationality and publishes many journals.
• A journal may cover issues in several research areas. It is
PT
important to store the order of appearance of research areas,
since these indicate their relative importance for the journal.
N
• It is important to keep track of the date on which a journal has
been borrowed and returned, and the member carrying out the
operation.
5
AreaOrder
-orderOfApperarance
1..* 1..*
Editor Journal Area
-editorName publishes Addressed in
-journalName -areaName
-nationality 1 * -ISBN -areaDetails
-shelf
EL
*
Operation
PT
Performs -date
operation -operationType
*
Member
N
-userName
-address
-birthDate
-phone
-email
6
Interface
• An interface in UML is a named set of operations.
• Interfaces are used to characterize some behaviour.
– Shown as a stereotyped class.
EL
Generalization can be defined between interfaces.
PT
<<interface>> CircularLinkedList <<interface>>
List
List
Add( )
isEmpty( ) N
…
7
Interface Example
• An interface specifies the set of services to be offered
by a class.
Cylinder
EL
<<interface>>
Shape
Draw
Pyramid
PT
Move
Scale
Rotate
Cube
N
Realization relationship
8
• A class realizes an interface if it provides Realizing an
implementations of all the operations. Interface
– Similar to the implements keyword in Java. CircularLinkedList <<interface>>
List
• UML provides two equivalent ways of
EL
denoting this relationship: CircularLinkedList
PT
List
Both represent: “CircularLinkedList
implements all the operations defined by
the List interface”.
N
9
Interface Dependency
• A class can be dependent on an interface.
– This means that it makes use of the operations defined in that interface.
EL
– E.g., the Restaurant class makes use of the List interface:
PT
Restaurant
<<use>>
N
List
10
Collection List
<<interface>> <<interface>>
Java Provides a
List interface for
AbstractList several
<<abstract>>
EL
implementations
PT
ArrayList Vector AbstractSequentialList
<<abstract>>
N Stack LinkedList
11
UML Packages
Account
• A package is a general purpose grouping
mechanism.
– Can be used to group any UML elements (e.g. use cases,
EL
actors, classes, components and other packages.)
PT
grouping of classes.
N
• A package does not necessarily translate into a
physical sub-system.
12
Mapping
MyPackage package MyPackage;
to Code
abstract class MyAbstractClass{}
MyAbstractClass
EL
class MyDerivedClass extends
MyAbstractClass{
MyDerivedClass
PT
int att;
att: int
myFunction()
N }
void myFunction() { .. }
13
• The B.Tech program of IIT Computer Science Department:
– comprises of many B.Tech batches. Exercise
• Each B.Tech batch consists of many B.Tech students.
EL
• CSE Department has many listed courses.
– A course is offered in many semesters
PT
– A course is either listed as an elective course or a core course.
N
• Each B.Tech student credits between 30 to 32 course offering.
14
Constraints on Objects
A constraint restricts the values that
objects can take.
EL
Example: No employee’s salary can
not exceed the salary of his boss.
PT
{salary <=boss.salary}
Employee
Salary
N
reports to
Employer
Salary
15
Abstract Classes
• Not allowed to have objects
instantiated from it.
EL
• Used only for inheritance purposes
PT
• Describes common attributes and
N
behavior for other classes.
16
Video Abstract Class
<<abstract>>
- Rental fee()
EL
PT
Blue Ray DVD
N
17
Why use abstract class? Abstract Class
− Reduces complexity of design
− Enhances understandability
EL
− Increases productivity
PT
It has been observed that:
− Productivity N
is inversely
proportional to complexity.
18
Another Abstract Class Hierarchy Diagram
Figure {abstract}
*
# position: Pos
+draw () {abstract}
EL
PT
Group Polygon
draw () N draw ()
19
Abstract public class Figure {
abstract public void draw(); Java Implementation
protected Pos position;
}
public class Group extends Figure {
private Vector <Figure> figures = new Vector <Figure> ();
EL
public void draw () {
}
PT
}
public class Polygon extends Figure {
} N
public void draw () { // draw polygon code
20
• Denotes poly (many) morphism (forms).
• Under different situations: What is
Polymorphism?
– Same message to the same object can
EL
result in different actions.
PT
• Two types:
• Static
• Dynamic
N
21
Class Circle{ An Example of Static
Binding
private float x, y, radius;
private int fillType;
public create ();
EL
public create (float x,float y, float ce
PT
public create (float x, float y, float c
}
N
22
Assume a class named Circle has three definitions
for create operation An Example of
− Without any parameter, default Static Binding
EL
− Centre and radius as parameter
− Centre, radius and fillType as parameter
PT
− Depending upon parameters, method will be
invoked N
− Method create is said to be overloaded
23
• Method call to an object of What is LibraryMember
EL
object of the derived class.
• Which principles are involved?
PT
UnderGrad PostGrad Research
– Inheritance hierarchy
N
– Method overriding
– Assignment to compatible types
24
Principle of substitutability (Liskov’s Compatible
substitutability principle): Types
− An object can be either assigned to or used
EL
in place of an object of its ancestor class,
but not vice versa.
PT
A A a; B b;
N
a=b; (OK)
B b=a; (not OK)
25
Liskov Substitution Principle (Barbara Liskov, 1988)
• If for an object a of type A there is an object b
of type B such that A is a subtype of B:
EL
– Then it is possible to use b for a.
PT
A A a; B b;
a=b; (OK)
B
N
b=a; (not OK)
26
• Any subclass object should be Or in Plain
usable in place of its parent class English
object.
EL
• Corollary:
PT
– All derived classes must honour the
contracts of their base classes
N
– IS A = same public behavior
27
Dynamic Binding
Exact method to be bound on
a method call:
EL
− Not possible to determine at
PT
compile time.
− N
Dynamically decided at runtime.
28
• Consider a class hierarchy of An Example of
different geometric objects: Dynamic Binding
EL
— Display method is declared in the shape
class and overridden in each derived class.
PT
—A single call to the display method would
N
take care of displaying the appropriate
element.
29
An Example of
Shape
Dynamic Binding
EL
PT
Ellipse Square
N Cube
Class hierarchy of geometric objects
30
Example Code
Traditional code Object-oriented code using Dynamic
Shape s[1000]; Binding
for(i=0;i<1000;i++){
Shape [] s=new Shape[1000];
If (s[i] == Circle)
EL
for(i=0;i<s.length;i++)
draw_circle(); s[i].draw();
PT
else if (s[i]== Rectangle)
draw_rectangle(); -
}
- N -
-
-
31
class Shape {
public static void main(String args[]){
void draw() { System.out.println ("Shape");
Shape[] s = new Shape[3];
}
} s[0] = new Circle();
class Circle extends Shape { s[1] = new Line();
void draw() { System.out.println ("Circle"); } s[2] = new Rectangle();
EL
} for (int i = 0; i < s.length; i++){
PT
class Line extends Shape { s[i].draw();
void draw() { System.out.println ("Line"); } // prints Circle, Line, Rectangle
}
N
class Rectangle extends Shape {
}
}
EL
Diagrams
PT
N
33
Stateless vs. Stateful Objects
• State-independent (modeless):
– Type of objects that always respond the same
way to an event.
EL
• State-dependent (modal):
PT
– Type of objects that react differently to events
depending on its state or mode.
N
Use state machine diagrams for modeling
objects with complex state-dependent behavior.
34
• Give examples of some classes that have non-trivial state
Stateful
models:
Classes
– Lift controller: Up, down, standstill,…
– Game software controller: Novice, Moderate, Advanced…
EL
– Gui: Active, Inactive, clicked once, …
PT
– Robot controller: Obstacle, clear, difficult terrain…
• Controller classes are an important class of stateful examples:
N
– A controller may change its mode depending on sensor
inputs and user inputs.
35
• In a client-server system: Stateful Objects
– Servers are stateless, clients are stateful.
• Common stateful objects:
– Controllers:
EL
• A game controller may put the game in expert, novice or intermediate
modes.
PT
– Devices:
• A Modem object could be dialing, sending, receiving, etc.
N
– Mutators (objects that change state or role)
• A RentalVideo is rented, inStore, or overDue
36
• Traditional programs have single flow of control
– Represented using flowchart or activity diagram Event-Based
Programming
• Event-driven systems :
EL
– In contrast, depending on an event occurrence,
corresponding handler is activated
PT
– Programming these using traditional approach often not
N
suitable, and would cause wasteful computations.
– Represented using state machines.
37
Why Create State Model?
• Tackle complexity
• Document:
EL
– For review, explaining to others, etc.
PT
• Generate code automatically
N
• Generate test cases
38
Finite State Automaton
• A machine whose output behavior is not
only a direct consequence of the current
EL
input,
PT
– But past history of its inputs
39
Basic State Machine Diagram
• Graphical representation of automata behavior…
EL
Any key/ Default Caps Lock
send-lower-
PT
Case-code
AnyKey/
N
Caps Unlock
CapsLocked Send-upper-
Case-code
40
Exercise 1: Draw State Machine •Press any key: lower
Diagram of a Keyboard? case ASCII code is sent
to computer…
•Once press the caps
lock key: upper case
EL
ASCII code will be sent
Any key/ Caps Lock on a key press…
send-lower- Default
Case-code
PT
AnyKey/
Send-upper-
Case-code
N
Caps Unlock
CapsLocked
41
Exercise 2: initial state •A library book to start
State Machine with, is present in a shelf…
Diagram of a •When borrowed out, it is
Library Book not on shelf…
•Returned, on shelf…
EL
On shelf state
PT
On loan
N final state
42
• Model a keyboard using UML Exercise 3
state machine diagram:
EL
key stroke.
PT
– Breaks down after entering
N
100,000 key strokes.
43
/n=0
Solution
[n=100,000] KeyStroke
Default
EL
keyStroke/
n++, transmit code
PT
Broken
N
44
Exercise 4: Draw State Machine: GUI Accepts only Balanced Parentheses
• Inputs are any characters
• No nesting of parentheses
• No “output” other than any state change
EL
(
PT
start Balanced Not
Balanced
end N )
* *
45
Example 5: Draw State Machine: GUI Accepts only upto 3 Nested parentheses
end
( ( (
EL
start
) ) )
) * * * ( *
PT
Error
How can we extend this machine
*
•
N
to handle arbitrarily deep nesting
of parentheses?
46
(/count++
How to Model
(/count=1
Nested
start OK Wait parentheses?
EL
end )[count==1] /count=0
)[count>1]/ count--
PT
• A state machine, but not just a state machine --- an
EFSM
N
• Addition of variables (“extended”)
47
FSMs suffer from a few severe shortcomings:
State Chart
• What are the shortcomings of FSM?
Diagram
EL
• State chart is based on the work of David Harel [1990]
PT
– Overcomes important shortcomings of FSM
N
– Extends FSM in 2 major ways: Concurrent states and
hierarchy.
48
• Power: On, OFF Robot: State Variables
• Movement: Walk, Run
• Direction: Forward, Backward, left, Right
How many states in
EL
• Left hand: Raised, Down
the state machine
• Right hand: Raised, down model?
PT
• Head: Straight, turned left, turned right
• Headlight: On, Off FSM: exponential
N
• Turn: Left, Right, Straight
rise in number of
states with state
variables
49
Event State
turnOn Activated
turnOff Deactivated (Idle)
stop Stopped
walk Walking
EL
run Running
raiseLeftArm LeftArmRaised
lowerLeftArm LeftArmLowered
PT
lowerLeftArm LeftArmLowered
raiseRightArm RightArmRaised
lowerRightArm
turnHead
N
RightArmLowered
HeadTurned(direction)
speak Talking(text)
50
• State chart avoids two problems of FSM:
– State explosion State Chart
– Lack of support for representing Diagram
EL
concurrent states
PT
• A hierarchical state model:
N
– Can have composite states --- OR and AND
states.
51