Lesson Summary Notes 1-10-OBJECT ORIENTED PROGRAMMING SLIDES NOTES UPDATED

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 116

Define terms

 Abstraction;
The most important aspect of a system model is that it
leaves out detail. An abstraction deliberately simplifies and
picks out the most salient characteristics.
 Encapsulation

Supports the notion of gathering together related aspects of


a design, grouping them and hiding the implementation.
 Coupling

Refers to the degree to which each program module relies


on each other module.
 Data Member
 An object will have a number of data members which define the data held by the
object.
 A class
 Is a template for the construction of an object. It defines the data an object stores
and the operations which can be applied to the data.
 An object
 Is an instantiation of a class. It has memory allocated to it to record its state. It
responds to messages passed to it. An object also has a number of member
functions which specify the nature of the operations on the object.
 In single inheritance
 A subclass may inherit data and operations from a single superclass
 In multiple inheritance
 A subclass may inherit data and operations from a number of superclasses.
 Aggregation
 Objects in the real world are often composed of different parts. For example, a
study pack for a course may be composed of a book, PowerPoint slides,
quizzes, and recommendations for further reading. Sometimes in a system
model, you need to illustrate this. The UML provides a special type of
association between classes called aggregation that means that one object (the
whole) is composed of other objects (the parts). To show this, we use a
diamond shape next to the class that represents the whole.
 Cohesion
 refers to the degree to which each part of a module is associated
with each other part, in terms of functional relation.
Needs for object oriented programming paradigm.
 The object oriented paradigm is a methodology for producing reusable
software components
 The object-oriented paradigm is a programming methodology that
promotes the efficient design and development of software systems
using reusable components that can be quickly and safely assembled
into larger systems.
 Object oriented programming has taken a completely different direction
and will place an emphasis on objects and information. With object
oriented programming, a problem will be broken down into a number
of units .these are called objects .The foundation of oop is the fact that
it will place an emphasis on objects and classes. There are number of
advantages to be found with using the oop paradigm, and some of
these are oop paradigm
 Object oriented programming is a concept that was created because of
the need to overcome the problems that were found with using
structured programming techniques.While structured programming uses
an approach which is top down, oop uses an approach which is bottom
Definition of terms
 Object oriented paradigm.

The object oriented paradigm is a methodology for


producing reusable software components
 Paradigm

It’s a way in which a computer language looks at the


problem to be solved.
 Class

The basic unit of code is the class which is a template


for creating run-time objects
Differentiate between fields and methods as implied in object
oriented in java
 Java classes contain fields and methods. A field
is like a C++ data member, and a method is like
a C++ member function. In Java, each class will
be in its own .java file.
The access level in fields and methods as implied in
object oriented in java

 • Private: accessible only in this class


 • (package): accessible only in this package
 • protected: accessible only in this package and in all
subclasses of this class
 • public: accessible everywhere this class is available
Explain what is meant by the term class member
visibility
 Within a class instance variables and methods
may be public, private or protected. Public
variables and methods are visible in code
external to the class. Private variables and
methods are only visible in code within the
class. Protected variables and methods are
visible within the class in which they are
declared and all subclasses of that class
The access level in each class as implied in object oriented in
java
 Each class has one of two possible access levels

 (package): class objects can only be declared and


manipulated by code in this package
 Public: class objects can be declared and manipulated by
code in any package.
 Object: Object-oriented programming involves inheritance.
In Java, all classes (built-in or user-defined) are
(implicitly) subclasses of Object. Using an array of Object
in the List class allows any kind of Object (an instance of
any class) to be stored in the list.
 However, primitive types (int, char, etc) cannot be stored in
Explain what you understand when a
method is made static
This is when it does not access any of the non-
static fields of the class, and does not call any
non-static methods.
Why is data hiding supported by many object oriented
programming languages?

 Data hiding is supported to prevent external


code accessing the internal methods and
variables of a class.
 It ensures that external code does not have
access to partial information. It ensures that
contracts between the provider of a class and
the user of a class are fulfilled.
the difference between an object in an object oriented language
and a variable in a structured programming language
 A variable is simply a name given to an area of
memory which the program will use. In a typed
 language the compiler is able to constrain what
type of data is placed into this memory location.
 An object also identifies an area of storage for
data, additionally however, it also determines
 what operations may be applied to that data.
features you would expect to be present in an object oriented design. Give an
example of how each feature is realised in an
object oriented programming language with which you are familiar.
Class
Class MyClass{..}

Object
MyClass myObject = new MyClass();

Method

Class MyClass{void myMethod()


{}}
Inheritance

Class MyClass{
Class MySubclass extends MyClass{}
how class creation is done in object
oriented and java
A class is created in the following way

Class <class name>


{
Member variables;
Methods;
}
the class variables
We use class variables also know as Static fields when we
want to share characteristics across all objects within a
class. When you declare a field to be static, only a
single instance of the associated variable is created
common to all the objects of that class.Hence when
one object changes the value of a class variable, it
affects all objects of the class. We can access a class
variable by using the name of the class, and not
necessarily using a reference to an individual object
within the class. Static variables can be accessed even
though no objects of that class exist. It is declared
using static keyword.
Discuss the class Methods variables briefly

Class Methods also known as Static


Methods.Class methods, similar to Class
variables can be invoked without having
an instance of the class. Class methods are
often used to provide global functions for
Java programs. For example, methods in
the java.lang. Math package are class
methods. You cannot call nonstatic
Methods from inside a static method.
Bundling code into individual software objects provides
a number of benefits.
 Modularity: The source code for an object
can be written and maintained independently
of the source code for other objects. Once
created, an object can be easily passed around
inside the system.
 • Information-hiding: By interacting only
with an object's methods, the details of its
internal implementation remain hidden from
the outside world.
Bundling code into individual software objects
provides a number of benefits
 • Code re-use: If an object already exists (perhaps written by
another software developer),you can use that object in your
program. This allows specialists to implement/test/debug
complex, task-specific objects, which you can then trust to
run in your own code.
 • Pluggability and debugging ease: If a particular object
turns out to be problematic, you can simply remove it from
your application and plug in a different object as its
replacement. This is analogous to fixing mechanical
problems in the real world. If a bolt breaks, you replace it, not
the entire machine.
Bundling code into individual software objects provides a number of benefits
 Encapsulation:Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined
outside the wrapper. • Access to the code and data inside the wrapper is tightly controlled through a
well defined interface.
 Polymorphism: Polymorphism (from the Greek, meaning ―many forms‖) is a feature that allows one
interface to be used for a general class of actions. The specific action is determined by the exact nature
of the situation. Consider a stack (which is a last-in, first-out list). We might have a program that
requires three types of stacks. One stack is used for integer values, one for floating-point values, and
one for characters. The algorithm that implements each stack is the same, even though the data being
stored differs. In Java we can specify a general set of stack routines that all share the same names.
 More generally, the concept of polymorphism is often expressed by the phrase ―one interface, multiple
methods.‖This means that it is possible to design a generic interface to a group of related activities. •
This helps reduce complexity by allowing the same interface to be used to specify a general class of
action. • Polymorphism allows us to create clean, sensible, readable, and resilient code.
 class Hierarchies (Inheritance):Object-oriented programming allows classes to inherit commonly
used state and behavior from other classes. Different kinds of objects often have a certain amount in
common with each other. means “submitting, without proper attribution, any computer code that is
directly traceable to the computer code written by another person.” I give students a failing course grade
for any cheating. Expulsion is also possible. This doesn’t help your job prospects.
The function of Casting in object oriented with Java
We can assign a value of one type to a variable of another type. If
the two types are compatible, then Java will perform the
conversion automatically. For example, it is always possible
to assign an int value to a long variable. However, not all
types are compatible, and thus, not all type conversions are
implicitly allowed. For instance, there is no conversion
defined from double to byte. But it is possible for
conversion between incompatible types. To do so, you
must use a cast, which performs an explicit conversion
between incompatible types
Explain the responsibility principle as used in object-oriented design by Java

 The chain-of-responsibility pattern is a design pattern consisting of a source of


command objects and a series of processing objects.
 Each processing object contains logic that defines the types of command objects
that it can handle; the rest are passed to the next processing object in the chain. A
mechanism also exists for adding new processing objects to the end of this chain.
 Primary motivation is the need for a platform-independent (that is, architecture-
neutral)language that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls.
 Objects with clear responsibilities
 Each class should have a clear responsibility.
 If you can't state the purpose of a class in a single, clear sentence, then perhaps
your class structure needs some thought.
 In object-oriented programming, the single responsibility principle states that
every class should have a single responsibility, and that responsibility should be
entirely encapsulated by the class. All its services should be narrowly aligned with
that responsibility.
Bundling code into individual software objects provides a number of
benefits. Explain these benefits
 Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the system.
 • Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
 • Code re-use: If an object already exists (perhaps written by another software developer),you can
use that object in your program. This allows specialists to implement/test/debug complex, task-
specific objects, which you can then trust to run in your own code.
 • Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply
remove it from your application and plug in a different object as its replacement. This is analogous to
fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
An instance or an object for a class is created in the following way <class name> <object
name>=new <constructor>();
 Encapsulation:Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse. One way to think about
encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily
accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper
is tightly controlled through a well defined interface. To relate this to the real world, consider the
automatic transmission on an automobile. It encapsulates hundreds of bits of information about your
engine, such as how much we are accelerating, the pitch of the surface we are on, and the position of
the shift.The power of encapsulated code is that everyone knows how to access it and thus can use it
regardless of the implementation details—and without fear of unexpected side effects.
 Polymorphism (from the Greek, meaning ―many forms‖) is a feature that allows one interface to be used f
a general class of actions.
 • The specific action is determined by the exact nature of the situation. Consider a stack (which is a last-in,
first-out list). We might have a program that requires three types of stacks. One stack is used for integer
values, one for floating-point values, and one for characters. The algorithm that implements each stack is th
same, even though the data being stored differs.
 • In Java we can specify a general set of stack routines that all share the same names.More generally, the
concept of polymorphism is often expressed by the phrase ―one interface, multiple methods.‖This means
that it is possible to design a generic interface to a group of related activities.
 • This helps reduce complexity by allowing the same interface to be used to specify a general class of actio
 • Polymorphism allows us to create clean, sensible, readable, and resilient code.
 class Hierarchies (Inheritance):
 • Object-oriented programming allows classes to inherit commonly used state and behavior from other
classes. Different kinds of objects often have a certain amount in common with each other.
 • In the Java programming language, each class is allowed to have one direct superclass, and each superclas
has the potential for an unlimited number of subclasses:
 • Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (curre
speed, current pedal cadence, current gear). Yet each also defines additional features that make them
different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; som
mountain bikes have an additional chain ring, giving them a lower gear ratio. In this example, Bicycle now
becomes the super class of Mountain Bike, Road Bike, and Tandem Bike.
class member visibility
Within a class instance variables and methods may
be public, private or protected. Public variables and
methods are visible in code external to the class.
Private variables and methods are only visible in
code within the class. Protected variables and
methods are visible within the class in which they
are declared and all subclasses of that class
Why is data hiding supported by many object
oriented programming languages
Data hiding is supported to prevent external code
accessing the internal methods and variables of a
class. It ensures that external code does not have
access to partial information. It ensures that
contracts between the provider of a class and the
user of a class are fulfilled.
the difference between an object in an object oriented language and
a variable in a structured programming language?

A variable is simply a name given to an area of


memory which the program will use. In a typed
language the compiler is able to constrain what
type of data is placed into this memory location.
An object also identifies an area of storage for
data, additionally however, it also determines
what operations may be applied to that data.
Features you would expect to be present in an object oriented design.
Give an example of how each feature is realised in an object oriented
programming language with which you are familiar
Responsibility principle as used in object-oriented design by Java
 The chain-of-responsibility pattern is a design
pattern consisting of a source of command
objects and a series of processing objects.
 Each processing object contains logic that
defines the types of command objects that it can
handle; the rest are passed to the next processing
object in the chain. A mechanism also exists for
adding new processing objects to the end of this
chain.
Responsibility principle as used in object-oriented design by Java

 • Primary motivation is the need for a platform-independent (that


is, architecture- neutral)language that could be used to create
software to be embedded in various consumer electronic devices,
such as microwave ovens and remote controls.
 • Objects with clear responsibilities
 • Each class should have a clear responsibility.
 • If you can't state the purpose of a class in a single, clear
sentence, then perhaps your class structure needs some thought.
 • In object-oriented programming, the single responsibility
principle states that every class should have a single
responsibility, and that responsibility should be entirely
encapsulated by the class. All its services should be narrowly
aligned with that responsibility.
generalization
This means that common information will be
maintained in one place only. This is good
design practice as it means that, I changes are
proposed, then you do not have to look at all
classes in the system to see if they are affected
by the change.
Generalization
Generalization

This means that common information will be


maintained in one place only. This is good
design practice as it means that, I changes are
proposed, then you do not have to look at all
classes in the system to see if they are affected
by the change.
The Object Constraint Language (OCL)

The Object Constraint Language (OCL) started as a complement of the UML


notation with the goal to overcome the limitations of UML (and in general,
any graphical notation) in terms of precisely specifying detailed aspects of a
system design. Since then, OCL has become a key component of any model-
driven engineering (MDE) technique as the default language for expressing all
kinds of (meta)model query, manipulation and specification requirements.
Among many other applications, OCL is frequently used to express model
transformations (as part of the source and target patterns of transformation
rules), well-formedness rules (as part of the definition of new domain-specific
languages), or code-generation templates (as a way to express the generation
patterns and rules).
Motivation: Why OCL is needed

Graphical modeling languages are the preferred choice for many


designers when it comes to define the structural aspects of a domain
(i.e., its main concepts, their properties and the relationships
between them). The most typical example of a graphical notation is
UML [21], specially its class diagram which is by far the most used
UML diagram [13]. Nevertheless, this facility of use comes with a
price. In order to keep the number of notational elements
manageable, language designers must limit the expressiveness of the
language. This means that graphical notations can only express a
limited subset of all the relevant information of a domain. This is
where OCL (and in general, any other textual language) comes into
play. They are a necessary complement of the UML (or other graphical
languages) notation in order to be able to precisely specify all detailed
aspects of a system design
Motivation: Why OCL is needed
As an example, take a look at the class diagram of Figure below that
will be used as running example throughout the This diagram is an
excerpt of the EU-Rent Car Rentals Specification an in-depth
specification of the EU-Rent case study, which is a widely known
case study being promoted as a basis for demonstration of product
capabilities. EU-Rent presents a car rental company with branches in
several countries that provides typical rental services. EU-Rent was
originally developed by Model Systems, Ltd.
This excerpt contains information about the rentals of the company
(Rental class), the company branches (Branch class), the rented cars
(Car ), the category to which they belong (CarGroup ) and the
customers (Customer ) that at some point in time may become
blacklisted (BlackListed ) due to delayed car returns, unpaid rentals,
etc. Each rented car has one or more registered drivers and a pickup
and drop off branch assigned.
In the context of the Object Constraint Language (OCL) define the following

 An invariant is a condition that can be relied upon to be true


during the execution of a program, or during some portion of
it. It is a logical assertion that is held to always be true during
a certain phase of execution.
 A precondition is a condition or predicate that must always be
true just prior to the execution of some section of code or
before an operation in a formal specification. If a precondition
is violated, the effect of the section of code becomes undefined
and thus may or may not carry out its intended work.
 A postcondition is a condition or predicate that must always be
true just after the execution of some section of code or after an
operation in a formal specification.
Explain how OCL might be used in the design of an object oriented program.

 It is good practice to produce a design for a program before coding


it.
 Typically in object oriented programming a design might be
realised by a set of Unified Modelling Language diagrams. The
class diagrams would set out the names of the classes, the names
of the variables and the names of the methods etc. Other diagrams
would indicate other aspects of the behaviour of the system. Many
of these diagrams are able to capture some aspects of the
constraints which apply to the system. UML diagrams, however,
are not sufficient to express all possible constraints nor are they
able to precisely state the constraints they can represent. OCL can
be used to provide further details of the requirements of system
which goes beyond what can be achieved in a UML diagram and
allows those details can be represented in a very precise way.
Programming Language Evolution
 Machine language
 Assembler
 “3rd generation” (COBOL, FORTRAN, C)
 Specialized (Lisp, Prolog, APL)
 “4th generation” (SQL, spreadsheets,
Mathematica)
 “5th generation” (example, anyone?)
Why So Many Languages?
 Bring the language “closer” to the problem.
 But 4GLs are typically focused on specialized
domains (e.g., relational databases).
 We want a language that is general purpose,
yet can easily be “tailored” to any domain.
Object-Oriented Languages
 Smalltalk, C++, Java, etc…
 You can make any kind of objects you want
 How different from procedural languages?
 No different at all: Every (reasonable) language is
“Turing complete”
 Very different: Make expression easier, less
error-prone
O-O Languages (Alan Kay)
 Everything is an object.
 A program is a bunch of objects telling each
other what to do, by sending messages.
 Each object has its own memory, and is made
up of other objects.
 Every object has a type (class).
 All objects of the same type can receive the
same messages.
Making Java Work
 It's “easy as pie” to write procedural code in
Java.
 It takes some discipline (an attitude) to think
O-O.
 It's worthwhile to do it.
Objects
 An object has an interface, determined by its
class.
 A class is an abstract data type, or user-
defined type.
 Designing a class means defining its
interface.
Built-In Types
 Think of an int…
 What is its interface?
 How do you “send it messages”?
 How do you make one?
 Where does it go when you’re done with it?
 In solving a computational problem, the goal
is to
 Dream up useful classes, and
 Endow them with appropriate characteristics.
Example
 Suppose I’ve defined this class in Java:
BottleOfBeer

+open():void
+lift(height:int):void
+tilt(angle:int):void
 To make one, I type
BottleOfBeer myBeer = new BottleOfBeer();
 If I want myBeer opened, I say
myBeer.open();
But Why Not Just…
BottleOfBeer myBeer;
 This is legal, but just makes a “reference
variable” named myBeer
 This variable can refer to any BottleOfBeer
object, but currently refers to nothing
 The operator new actually causes an object to
be created, so we tell it what kind we want
Designers Design, Users Use
 The interface is the critical part, but the details
(implementation) are important too.
BottleOfBeer

-topOn:Boolean

+open():void
+lift(height:int):void
+tilt(angle:int):void

 Users use the interface (the “public part”); the


implementation is hidden by “access control”.
Objects vs. Procedural Libraries
 C libraries are like this, sort of:
 The library designer invents a useful struct.
 Then she provides some useful functions for it.
 The user creates an instance of the struct, then
applies library functions to it.
 One big difference is that anyone can change
any part of the struct. Booo, hsss!
 Another difference is in initialization.
Two Ways of Reusing Classes
 Composition: One class has another as a part
(indicated by the diamond “aggregation”
symbol).
BottleOfBeer CaseOfBeer Tavern

+open():void
+lift(height:int):void
+tilt(angle:int):void

Patron
Two Ways of Reusing Classes
 Inheritance: One class is a specialized version
of another (indicated by the triangle
“inheritance” symbol).
BottleOfBeer
BottleOfRollingRock

-lowCalorie:Boolean
+open():void
+lift(height:int):void +isLowCalorie():Boolean
+tilt(angle:int):void
Polymorphism
 Different subclasses respond to the same
message, possibly with different actions.
Patron

+beerPlease():Polite

AmericanPatron BritishPatron GermanPatron

+beerPlease():Rude +beerPlease():InGerman
Some Java Code
Patron p1 = new Patron();
Patron p2 = new YankPatron();
Patron p3 = new BritPatron();
Patron p4 = new GermanPatron();
p1.BeerPlease() // polite request
p2. BeerPlease() // rude request
p3.BeerPlease() // polite request
p4.BeerPlease() // request in German (but polite)

 This is a bit of a trick: it requires late binding of the


function call.
Creating Objects
 We usually assume this is free; with built-in
types like int or char, we just say
int i;
char c;
 With user-defined types (the ones we make),
we need to be explicit about what we want:
 constructor function
 This is a very important issue!
Destroying Objects
 If an object goes “out of scope,” it can no
longer be used (its name is no longer known).
 In C++, we might need to write an explicit
function to free memory allocated to an
object.
 Java uses references and “garbage collection”.
Example of Object Scope
public String getTitle(int lectureNumber) {
LectureNotes lect;
lect = syllabus.getLecture(lectureNumber);
String s = lect.getLine(1);
return s;
}

 What happens to lect?


 The LectureNotes object still exists, but the reference
lect disappears (it’s out of scope after return).
 Eventually, the garbage collector removes the actual
LectureNotes object.
Java’s Primitive Types
Type Size Wrapper type
boolean - Boolean
char 16-bit Character
byte 8-bit Byte
short 16-bit Short
int 32-bit Integer
long 64-bit Long
float 32-bit Float
double 64-bit Double
void - Void
Creating New Types
class MyNewType {
// definition here
}
 Now it’s legal to say
MyNewType m = new MyNewType();
Class Members
 Fields (a.k.a. member variables, data
members)
 Methods (a.k.a. member functions)
class MyClass {
int a;
YourClass b;
float memberFunction(int x, float f) {
return 0;
}
}
The Major Issues
 Editing
 Use any text editor you like (not a word processor!); save
as HelloDate.java
 Compiling
 From a DOS or UNIX command line, type
> javac HelloDate.java
 This should produce the file HelloDate.class
 Running
 Again from the command prompt, type
> java HelloDate
Introduction to Introduction to UML
UML or Unified Modelling Language is a multipurpose modelling
language that aims to provide a standard for modelling a system.
UML consists of various diagrams used to model a system from
initial idea to an implement able project. Each model carries the
specifications and requirement of that same system from different
point of view. For example, the users of a particular system only want
to know what the system can do while the designer will design what
and how many functions or tasks in that system. But a programmer or
engineer needs to know how to perform a particular function or how
each task affect each other. All this can be realise using UML
diagrams. UML provides standard methods and notation to create
these models as well as guideline to transform one model to another
model while preserving the consistency between models.
Introduction to Introduction to UML
UML is a collaboration of several traditional modelling concepts and
notation. It is first created by Grady Booch, James Rumbaugh and Ivar
Jacobson during 1994. UML is a non proprietary modelling language but
its ownership and evolution responsibility is governed by Object
Management Group (OMG). The application of UML is very wide. It is
not only used in object oriented systems analysis and design. It is also
used widely in all phases of complex software development life cycles,
development of many systems engineering, as well as in modelling of
many business processes. UML is not dependent on any programming
languages and strongly highlight the concept of reuse, layering,
partitioning and modularity. In general, UML is design to be flexible,
extendable and open to many specific applications or industries. UML
provides guideline on how to extend a system using stereotypes method.
According to the new OMG’s information [1], there are a total of thirteen types of
diagrams define in the latest UML 2.0, which is divided into three categories
namely static structure, behaviour and interaction. Static structure models include
the Class diagram, Object diagram, Component diagram, Composite Structure
diagram, Package diagram, and Deployment diagram. Behaviour models include
the Use Case diagram, Activity diagram, and State diagram. And lastly interaction
models include the Sequence diagram, Communication diagram, Timing diagram,
and Interaction Overview diagram. Each of the diagrams serves its own purpose
and is strongly related to each other. The details of Use Case diagram and Class
diagram will be discussed in later sections.
Structural or static modelling consists of diagrams that is used to shows elements
or functions and its relationships which a system have. In other words, it is used to
shows different view of ‘what’ the system have or do, as well as the relationships
but not what happen from the interaction. Class diagram, being one of the static
model, uses set of classes to group objects with common properties together and
shows the relationships between each class. Package diagram is a simplify version
of complex class diagram, where related classes can be group into individual
package. A dotted line is used to indicate there is a dependency among packages.
Object diagram shows instances or objects generated from particular classes. It is
useful in explaining complex
recursive relationships between classes in class diagram. Figure 1
shows some simple example of the diagrams.
Class diagram, Package diagram and Object diagram are usually
used during analysis and design stage. On other hand, Component,
Composite Structure and Deployment diagrams are used in
implementation stage or when the system is complete. Component
diagram gives a view of what components (or pieces of parts) and its
relationships that is inside the completed system. While Deployment
diagram shows how to assemble these components together to form
the systems or where these components belong to. Lastly, the OMG
UML superstructure V2.1.2 [12], define a Composite Structure
diagram as to depict the internal structure of a classifier, as well as
the use of collaboration in a collaboration use. Figure 2 shows simple
example of Component, Deployment and Composite Structure
diagrams.
Example of Component, Deployment and Composite Structure diagrams

In addition, behaviour modelling show how each


elements or functions in a system will behave or
interact with each other. Use case diagram depict the
functionality of a system with its users interaction.
Statechart (also call State Machine) diagram shows
the possible states of an object in a system and the
transition that cause the change of state[4]. Activity
diagram models how the control flows from one
activity to another within a single process or function
of a system.
Example of Component, Deployment and Composite Structure diagrams

Next, the interaction modelling category shows more details


behaviour of things derived from the general behaviour models
mentioned earlier. Sequence diagram shows step by step
operations flow and the messages passes between lifelines or
objects. Sequence diagram usually involve timing concept.
Communication (also known as Collaboration) diagram also
shows the messages passes between objects but it focus on the
objects role rather than the timing concept. Timing diagram focus
on events or conditions changes within objects and it time of
occurrence. Lastly, an Interaction Overview diagram shows the
overall flows control within the whole system which is a simplify
version of all Activity diagrams of the system. Figure 3 shows
simple example of behaviour and interaction type diagrams.
Example of behaviour and interaction models
Use Case Diagram
It is graphical overview the functionality and
requirement of the system and the interface with outside
the system, as well as it shows the actors and the
relationship between the actors and the use cases. Use
case diagram shows the design features. Moreover, the
use case diagram is the first point when designing new
system by using UML and when explaining the
requirement for the system in analysis, implementation
and documentations stage. Furthermore, the use case
diagram used to understand the system and what system
is. The use case diagram has four components: 1- Actor
2- Use cases 3- System boundary 4- Relationship
Actor:
“It represents role that can play with regard to a system”
[16], or it is external entity that interact with the system.
Furthermore, it is the input and the output of the use
case, and simple actor may achieve many use cases. The
actor includes Person, organization, hardware, software
or any external system that interact with the system.
Furthermore, the only relationship between the actors is
the generalization this is helpful to classifying overlap
roles between actors and the relation between the actor
and the use cases are association. Moreover, the Actor is
represented by stick man figure with suitable name that
portray the function as the user of the system and it is
write below the figure and the relation represent by line.
Use cases:
The use cases are sequence of actions that the user
takes on a system to get particular target and it
describe the interaction between the actor and the
system, as well as is method for capture the task
requirement of a system. Moreover, use cases
explain what the system wants to do without
identifying how the system will execute. The use
case is represented by ellipse with name that includes
an active verb and usually a noun phrase and it is
help to understand the functional requirement of a
system.
System boundary:
“System is a piece or multiple pieces of software that
perform some sort of function for its users” [15].system
boundary boxes is separate between the actors and the use
cases and it represent by rectangle around the use cases of
the system which is the part of the system and the actors
are out side the rectangle which is external to the system,
actors are joined with the use cases by lines. Moreover,
the name of the system boundary is written inside the box
Furthermore, system boundary boxes are rarely used.
Relationships

The relationship is the association between the actors as well as it illustrate the actors that
are participating in a use case. Moreover, the use cases and the path relationships are
attach the diagram together. The purpose of the relationship is to explain that an actor is
basically involved in a use case, not involve an information exchange in any direction.
Relationships are represented by a line connecting between Actors and use cases. T
he relationships between use case diagrams in UML have different type: 1- Includes
relationship. 2- Extends relationship. 3- Generalizations relationship.[16][15]

Include relationship:- The include relationship is used to indicate that one use case has
explicitly contains the behavior of another use case to execute its function. Moreover,
include relationship has two types of use cases that illustrate this situation, firstly
including use case which required the functionality from another use case, and the second
kind included use case which is included in the first, including use case. The includes
relationship is represented by dashed line with open arrow head which connected the
include use case including use case started at including use case and ending at the include
use case, as well as the ward <<include>> enveloping with guillemot is written Along the
line . When develop the system into an application the included use case is facilitated to
identify where can reuse functionality, which is major, advantage of design and
development.
Extend relationship:
The extended relationship is used to indicate that use case
completely consists of the behavior of another use case at one or
specific point, which mean inheritance between the class in C++.
The notation of extended relationship is similar that to include
relationship. Furthermore, the use case of the include relationship
might totally use again with another use case behavior but in the
extended relationship the reuse was optional depended on system
achievement decision ,as well as the Extends relationship is a
conditional include . Extends relationship is represented by
dashed line with an open arrow head and along the line is written
“<<extend>>", enclosed in guillemets. An extend relationship
points the line started at the use case which is conditionally
include the other use case. [16][15]
Generalizations relationship:
The generalization relationship is used to represent that the
parent use case identify behaviour that its children can
inherit, and the child can add or override to that behaviour,
as well as Generalization can be related to both actors and
use cases to represent that the child inherit functional from
parent .Furthermore, Generalization can separated more
than two child use case as well as generalization can be
hierarchal. Moreover, the use case inheritance is helpful to
show that one use case is special kind of another use case.
The generalization relationship is represented by a solid line
with a hollow triangular arrow. The arrow is drawn
indicating the direction of the Generalization.[16][15][17
Class Diagram
The system static structure can be documented by
class diagram. All system life time can be shown on a
links (associations) between classes with their
operations, attributes, and names. Class diagram
define as a rectangular boxes .This boxes initially
contain sections. First section gives for class name (or
object name), second one contain the class attributes,
and the bottom section for methods (operations)
associated with the class as shown below
Each object has a class in class diagram .This object
may be a person, thing, place, or event for our
system. In attribute section (…) indicate that there
are other attributes related to that class. Before build
a class, you should make a good class model that
help to understand the system behavior. The class
must meet all the system criteria, and realize the use
case diagram, otherwise that the class model can not
work well, whatever the techniques are used to build
the class
The class building should:
• Design it in cheap and quick ways, this mean each point required in
system behavior must provide in sensible way, by the object of the
class.
• Design a system to easy maintain and flexible to add future
requirements. If object needs to update ,this should be easily done
and should the designer keep a track to that object for any new
changes ,such as when the super market change the item cost ,the
updated values carry on directly to the system data base without need
to make a new design or add other class for that! .
A good class represents permanent classes of domain objects,
which do not depend on particular function, this mean a name
of class to call it is need to be clearer .example in the member
class for library system gives the indication of the class
contents rather than call the class moon, people in library or
any name not related to class attributes! • The design of
classes should be chooses carefully and makes sure each class
has a link with other class. Do not build a class without have
work to do it. • The model design must contain all the
description of what should the system do. • The class name
should be a noun. The attributes are name phrases, the
methods have a verb sentences, and the links (association)
between that classes contain the exact operations between
them such as: is a , part of, contain, has a …etc.
Attributes
Any class cannot make it process without
addressing the states and behavior of that object.
It should have the attributes middle section of
object (or class) box with lower case letter for
each name. Each object have own attributes and
they gives the all information that object have. In
library system the member object attributes are:
member ID, member name, address, phone no. ,
e- mail. All those have unique information for
each member in library.
Attributes
Some attributes values could be changes during system life
time and this should included in the first steps of building a
system class diagram as we mentioned in good class points.
In library, sometimes the member changes the phone no. or
address ,but in address changes ,the good actor(designer) for
class design need to add new class name address .Because
the addresses have complex lines and many information, also
the address object could be used from other class not for
member class only .It may use for librarian class. This
method reduces the interactions loads on system behavior.
Some type of class diagram add the attributes information
within class diagram like member class, also can but the
programming languages arguments such as title: string,
name: char ….etc as show in copy class below
Multiplicities
Operations
Operations are located in third (bottom) class section. They
must define in each class box, because the object (class) did
not know what should do and which other class should
interact with. The operation tells object what is the message
passed to the receiver object, and the last one invoked that
message to perform operation. The familiar format for
operation as shown in fig 4 gives (visibility name
(parameters): type), Take a copy() :char There is a tight
relationship between object state and operation .the object
attributes can not change or update it values by it self.
The object needs to have a service that wraps the assists modularity
in a system life time. This service can provide it only at object’s
interface .It contain a signature for each operation to avoid the
conflicting during sending or receiving messages between system
objects. Normally the object just respond to a simple quires .There
are objects need to send a message that have a valid call on an
operation.
The operations write in verb sentences lower case letters to give the
indicate about what the class (object)need to do and which other
class(receiver class)operations or attributes are related to that
operations .In class diagrams the generalization operation gives
important concepts. In library system we can call a library member
is generalization of librarian, because each librarian is already a
member of library. This go to other class diagrams relations such as,
aggregation, composition, association class, interface, and others.
They classified in table below.
Generalization:
Generalization: in example below, the engineer, and doctor are goes to
one people (human) class .they generalize, or inherit a people. We can
call doctors, engineers, teachers are people, but never called the people
are doctor! Generalization goes in one way from children class to
parent’s class.
Aggregation:

Aggregation: Is represented by empty diamond.


The seat is an aggregate of car .This mean if the
seat class damaged, the car class still exist.
Composition:

Composition: It represented by solid diamond.


The engine is composed of car. Mean if the
engine class damaged, the car also will damaged
as well .
Associations:
Associations: the UML versions implement different types of
association operations. The basic concepts that labeled the association
between classes called (role names) .it give multiplicity constraints [6].
Some versions noted two associates between two objects for cost
effective of system, and label each one if the class have references from
many classes such as company and client class as shown.
Associations
For first association ,the one to one cardinality means for each
company there is only one contact person for each company,
in second association means there is zero or many employees
in one company. This example shows how add two attribute
that referenced to other class [10]. Operations not end in above
examples .They are the general operations used ,but there are
many of them used for advanced steps depends on how the
system life time work and system needs for other operations
such as, association with multiplicities and navigability(look
like associations but with one link between classes), interfaces,
pattern, and qualified association. The good system works
perfectly if it build as simply as possible to understand it from
others (clients), and easily to upgrade, updates, and
Relationship between Use Case and Class Diagram

The use case diagram is usually deployed at the very beginning


stage of any project. Use case diagram only shows what is the
function and requirement of a system. Hence, the next stage of
the project implementation will be transform the use case
diagram to others diagram (usually another type of UML
diagram) closer to its project implementation. This process is
called realisation. One of the most popular diagrams used will be
Class diagram. Following will be some guideline for use case
realisation. Almost everything in UML is optional, hence it is not
a necessary step to follow. First, identify possible set of classes
that can derived from the use case diagram. Then understand how
those classes might relate to deliver the functionality of the use
case.
Relationship between Use Case and Class Diagram

All details that are not directly related to the collaboration will be
suppressed. At this stage, the class diagram might not really tell the
whole story of the system. But as the design continues, more
information will be added. The diagram will eventually form the
picture as the model transform again. It is very important that the
consistency of all diagrams used is maintained especially during the
realisation process. At the end of realisation process, both the use
case and class diagram should have structural and notational
similarities to the collaboration. There should be a class for each
nodes and each classes have associations that link them. Some class
might not have any relationship yet but will be added in later stage.
The end result must have all class correspond with a relationship
Discuss how object oriented code can be tested; within your
answer explain which.UML diagrams can be used to aid testing.

 An open-ended question. The Candidate may look at different


approaches, for example:
 · Fault based testing
 · Scenario based testing
 ·Sequence Diagrams
 Or may discuss black-box and white-box testing with respect to
OO programming.
 The candidate must discuss which UML diagrams can be used
for testing, e.g., Use Case scenarios
Describe the way in which the Unified Modelling Language (UML)
can be used to design an object oriented program.
 1 An external perspective, where you model the context or
environment of the system.
 2. An interaction perspective where you model the
interactions between a system and its environment or
between the components of a system.
 3. A structural perspective, where you model the
organization of a system or the structure of the data that is
processed by the system.
 4. A behavioral perspective, where you model the dynamic
behavior of the system and how it responds to events.
Construct a UML class diagram showing the structure of a
professional society, wherein members pay an annual fee.
Your class diagram should incorporate the following 6
classes: member, studentMember, standardMember,
seniorMember, society, and governingCommittee, which
should be connected with appropriate relationships, and be
populated with appropriate instance variables and methods
to enable the names, addresses and fees of members to be
stored, along with the management committee members, and
the name and HQ address of the society. The governing
committee will comprise a number of senior members
 Above is shown valid basic structure for the class diagram;
any reasonable variant would also be accepted. If the
candidate correctly assembles a member inheritance
hierarchy and uses the correct symbols for inheritance, up to
3 marks were awarded. If the candidate has other appropriate
relationships connecting the member hierarchy to the other
classes, including their multiplicity, up to 3 marks were
awarded. If the candidate peppers the classes with appropriate
instance variables and methods, and correctly designates
them as private, public or protected, up to 2 marks were
awarded.
A colleague suggests that the member class is abstract. What do they mean by this,
and how is an abstract class represented in a UML class diagram?

The member class is abstract because it is the super-


class of an inheritance (generalization) for
specification hierarchy, giving rise to sub-classes
standardMember and seniorMember. It will never be
instantiated, and is there to hold shared properties
between standardMember and seniorMember classes
only, and potentially to define methods that must be
implemented by those sub-classes.
The Unified Modelling Language 2.0 (UML) comprises of 13
different diagrams. These can be broadly categorised as: i)
Behaviour diagrams ii) Structure diagrams iii) Interaction
diagrams (a) For each category, give a description of one diagram
that falls into the category; include a simple example of its use
and explain when you would use it.
 The following indicate examples of the types of diagrams which
fall into each category:
 Behavior Diagrams emphasize what must happen in the system
being modeled:
 · Activity diagrams, which show the activities involved in a
process or in data processing
 · State diagrams, which show how the system reacts to internal
and external events
 Use case diagrams, use case modeling is widely used to support
requirements elicitation.A use case can be taken as a simple
scenario that describes what a user expects from a system.
 Structure Diagrams emphasise what things must be in the system being modeled:
 · Class diagrams, which show the object classes in the system and the associations between these classe
 · Component diagram
 · Composite structure diagram
 · Deployment diagram
 · Object diagram
 · Package diagram
 Interaction Diagrams, a subset of behavior diagrams, emphasize the flow of control and data
 among the things in the system being modeled:
 · Collaboration (UML 1.x)/Communication diagram (UML 2.0)
 · Interaction overview diagram (UML 2.0)
 · Sequence diagrams, which show interactions between actors and the system and
 between system components
 ·Use case diagrams, which show the interactions between a system and its environment and is widely used to support
requirements elicitation.A use case can be taken as a simple scenario that describes what a user expects from a
system.
 · UML Timing Diagram (UML 2.0)
 For each category, the student should give a short description of one of the diagrams, include a
 simple example and say when they should be used.
:
Given the following UML diagram
 Explain the following OCL statement:
 context Train Journey

 inv: passengers->size() <= train.number Of


Seats
Answer
 The constraint says that for any train journey,
the number of people travelling on a train
making
 The journey must be less than or equal to the
number of seats on that train
Draw a use case diagram for the library system
Write down a use case description of the way a member borrows a book. Your
answer should include a normal sequence and three alternative sequences
 Sample use case description:
 Pre-Condition
 A member is registered with the library
 Actor Action System Response
 1. User requests to borrow a book 2. Check libaryId is valid and provides
libraryId
 3. Check user not exceeded their maximum limit
 4. Check user has no fines
 5. If ok, book is loaned to user and return date allocated
 Alternative sequences
 Step 2. Invalid card, loan refused.
 Step 3. User has exceeded limit, loan refused.
 Step 4. User has fine, loan refused.
 Step 6. Request printout of loans

You might also like