Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

• A square is a polygon Identify Classes

• Shyam is a student and Relations


• Every student has a name

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
• composition has a capital cityhere country is a class and capital city is a class and ‘has a’ indicates an aggregation or
relation and since the country has exactly one capital city, a capital city and therefore
we will use a composition relation here, country is composed of a capital city. Identify Classes
• A dining philosopher uses a fork Here philosopher is the class and fork is a
& Relations
class and ‘uses’ is a association relationship and dining is a qualifier for the philosopher, it is an adjective
and therefore this is the attribute of the philosopher, the state of the philosopher,what is he doing, so that becomes an attribute.
• A file is an ordinary file or a directory file the ‘is an’ is a giveaway for inheritance relation and therefore a file is a
generalconcept and then we can have special files like ordinary file and directory file
A file contain, files contain records, the contain is a aggregation and we draw it asa file contain many
• Files contain records records. We can just draw it here, we will draw here file contain many records

• A class can have several attributes This is not a aggregation, but it is an attribute is a data member of the class.

• A relation can be association or generalizationA relation can be association or generalization. Here relation is
a more general concept and association and generalization are special types of relation. Association is a relation and
generalization is a relation and therefore,this is a inheritance relation.

• A polygon is composed of an ordered set of points


pointi s a class and polygon is a class and this is a composition relation, assuming that once we drawthe polygon we don’t change the number of
points
• A programmer uses a computer language on a project association between ‘programmer’ and ‘computer
language’ and‘computer language’ and ‘project’, so there are three classes here, the ‘programmer’,‘computer language’ and ‘project’.

2
Exercise 1: Draw UML Diagrams
Some persons keep animals as pets.

EL
* > * Animals

PT
person
keeps

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
employees.

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 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 important to store the
order of appearance of research areas, since these indicate their relative
importance for the journal.
• 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
Aggregation in object-oriented
programming represents a
relationship where one object can
exist independently of another. It
involves composing different
abstractions together to define a class.
In a class diagram, aggregation is
depicted by an edge with a diamond
end pointing towards the superclass.
For example, in a "Library
Management System," classes like
User, Book, and Librarian are part of
the aggregation relationship with the
superclass.

Multiplicity refers to the number of elements of one class associated with another class. This association
can be one-to-one (1), many-to-many (*), or many-to-one/one-to-many (1 or *). For instance, in the
diagram, many users are associated with many books (denoted by *), indicating a many-to-many
relationship. One user has only one account (denoted by 1), indicating a one-to-one relationship. Many
books are associated with one librarian, representing a many-to-one or one-to-many relationship. These
relationships are visually represented in the diagram.
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.similar to
java interface
• Interfaces are used to characterize some behaviour.

EL
– Shown as a stereotyped class.
• Generalization can be defined between interfaces.

PT
<<interface>> CircularLinkedList <<interface>>
List
List dotted arrow here it is the implements, it is not
derived it is implements relation between the
Add( )
isEmpty( ) N interface class and circular linked list class.

7
Interface Example
• An interface specifies the set of services to be offered by class
An interface to think of it,it characterizes some behaviour and we can say that one class needs to provide a set
ofbehaviour and then we can represent the behaviour interface and other classes which need to provide .
Cylinder

EL
<<interface>> It helps a set of classes to provide
Shape a standard set of methods or a
standard behaviour.
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 representation of package

Account
• A package is a general purpose grouping audit package, payments,
receivables
mechanism.
– Can be used to group any UML elements (e.g. use cases,

EL
this package corresponds to
actors, classes, components and other packages.) a Java package so we can
have the UML package to
• Commonly used for specifying the logical

PT
indicate the classes which
are present in a specific Java
grouping of classes. package,

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
•Aggregation program of IIT Computer Science Department:
relationship between the department, the department has a program the association between the
department and the program and the program has many batches,
– comprises of many B.Tech batches. Exercise
here the department and course there is association but the semester in which it is offered can be in an association class.
• 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.
here there is a aggregation of a student and the number of courses,

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 .objects
An abstract class is not allowed to have
instantiated from it, only concrete
classes can have object instances
instantiated from it.

EL
• Used only for inheritance purposes

PT
• Describes common attributes and
N
behavior for other classes.

16
Video Abstract Class
<<abstract>> wewrite the specific stereotype within this angled brackets that is the
UML syntax

- 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 contains may figures Polygon special type of figure

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: it is called a static binding because based on the parameters it is determined
which method we are calling and it will be bound to that method, whether it is the
one body methods body associated with this one,the second one or the third one.

• Dynamic
N
• Static also static binding
static polymorphism the behaviour is decided at the compile time,in static polymorphism it’s defined
permanently for an object at the compiletime whereas
the dynamic polymorphism it is define dynamically at the runtime.

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
an ancestor class: What is LibraryMember

– Results in invocation of Dynamic


Binding?
the method of an appropriate object of
Faculty Students Staff
the derived class.
Which principles are involved?
– Inheritance hierarchy
• – Method overriding UnderGrad PostGrad Research
– Assignment to compatible types
array of library members and then we create various types of objects,maybe faculty
members, undergraduate members, post graduate members, staff members and so on.
Now, these objects are residing here, basically the array or the array list is of the type library member and now if we invoke an overridden
method here, let say issue book is overridden method the library member has a default issue book and then the faculty can issuelet say 10
books undergraduate student 5 book, post graduate 7 book research let say 8 books. Now depending on the object that is residing here in
this array, the corresponding issue method will be called, if it is a faculty object, which is residing in this array,then the faculty issue book
will be called even though the type of the array is library member.

24
Principle of substitutability (Liskov’s Compatible
substitutability principle): Types
− An object can be either assigned to or used
in place of an object of its ancestor class,
but not vice versa.
if B is a derived class of A

A A a; B b; a derived class object is compatible with its base class


object but not vice versa

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
— Display method is declared in the shape
class and overridden in each derived class.

—A single call to the display method would


take care of displaying the appropriate
element.

29
An Example of
Shape
Dynamic Binding

Circle Rectangle Line

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)
for(i=0;i<s.length;i++)
draw_circle(); s[i].draw();
else if (s[i]== Rectangle)
draw_rectangle(); -
-
-
-
} -

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 {
}
}

void draw() {System.out.println


("Rectangle"); } class diagram ends here

} 32
ƐƚĂƚĞŵĂĐŚŝŶĞĚŝĂŐƌĂŵŝƐƵƐĞĚƚŽŵŽĚĞůƚŚĞĚLJŶĂŵŝĐďĞŚĂǀŝŽƌŽĨĂĐůĂƐƐŝŶƌĞƐƉŽŶƐĞƚŽƚŝŵĞ
each and every class has a state but we don’t model every class using State Machine diagrams
We prefer to model the states with three or more states.

State Machine

EL
Diagrams

PT
Behavioral Diagram

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
state machine model is an extension of the 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

• Characterized by an internal state which


captures its past history.
N
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

Returned Borrowed transition


discarded

PT
On loan

N final state

42
• Model a keyboard using UML Exercise 3
state machine diagram:

– Transmits key code on each

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
( ( (

OK Wait 1 Wait 2 Wait 3

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
One of the very serious shortcomings of the state machine diagram is explosion of states. The number of
state increases very rapidly. For complex system, it can have thousands of states

• What are the shortcomings of FSM?


second problem with the traditional finite state machines is that we donot have concepts of a concurrent state.
ie ..lack of support for concurrent states.
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
.If it has n state variables and each state variable has two values,
• Movement: Walk, Run then how many stateswill be required to model the behavior of
the robo? It will be 2 to the power n.
• 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 If each statevariable can
take three states and there
• Headlight: On, Off FSM: exponential are n state variables, how

N
• Turn: Left, Right, Straight
rise in number of
states with state
many states will be neededto
model the behavior of the
robo? It will be 3 to the
variables power n.

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

You might also like