0% found this document useful (0 votes)
1 views71 pages

Object Oriented Programming Systems

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts, including encapsulation, inheritance, and polymorphism, along with programming design methods such as structured and modular programming. It also covers the Unified Modeling Language (UML), collections framework, process models, and testing methodologies related to OOP. Additionally, it discusses various programming language modifiers and their implications on class and method accessibility.

Uploaded by

hlt.ariapala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views71 pages

Object Oriented Programming Systems

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts, including encapsulation, inheritance, and polymorphism, along with programming design methods such as structured and modular programming. It also covers the Unified Modeling Language (UML), collections framework, process models, and testing methodologies related to OOP. Additionally, it discusses various programming language modifiers and their implications on class and method accessibility.

Uploaded by

hlt.ariapala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

[Type text]

Accredited Course Provider

TABLE OF CONTENTS
1. INTRODUCTION .......................................................................................................................................... 3
1.1. COMPUTER PROGRAM .............................................................................................................................. 3
1.2. PROGRAM DESIGN METHODS................................................................................................................... 3
2. CONCEPTS .................................................................................................................................................... 5
2.1. ENCAPSULATION ...................................................................................................................................... 5
2.2. MODIFIERS ............................................................................................................................................... 5
2.3. INHERITANCE ......................................................................................................................................... 12
2.4. POLYMORPHISM ..................................................................................................................................... 14
2.5. INTERFACES ........................................................................................................................................... 15
2.6. PACKAGES .............................................................................................................................................. 17
3. INTRODUCTION TO UNIFIED MODELING LANGUAGE (UML) .................................................. 19
3.1. HISTORY OF THE UML ........................................................................................................................... 19
3.2. BRIEF OVERVIEW OF UML ..................................................................................................................... 19
3.3. CONCEPTUAL MODEL OF UML .............................................................................................................. 20
3.4. DIAGRAMS IN UML 1.5 VERSION .......................................................................................................... 20
3.5. USE CASE DIAGRAMS ............................................................................................................................. 21
3.6. CLASS DIAGRAMS ................................................................................................................................... 23
3.7. PACKAGES AND OBJECT DIAGRAMS ...................................................................................................... 25
3.8. SEQUENCE DIAGRAMS ........................................................................................................................... 27
3.9. COLLABORATION DIAGRAM................................................................................................................... 28
3.10. STATE CHART DIAGRAMS ...................................................................................................................... 29
3.11. ACTIVITY DIAGRAMS ............................................................................................................................. 30
3.12. COMPONENT AND DEPLOYMENT DIAGRAMS ......................................................................................... 32
4. OBJECT ORIENTED PROGRAMMING CONCEPTS ......................................................................... 33
4.1. WHAT IS AN OBJECT?............................................................................................................................. 33
4.2. WHAT IS A CLASS? ................................................................................................................................. 33
4.3. INSTANCE VARIABLES. ........................................................................................................................... 34
4.4. CLASS VARIABLES .................................................................................................................................. 34
4.5. LOCAL VARIABLES ................................................................................................................................. 35
4.6. CREATING METHODS .............................................................................................................................. 35
4.7. VARIABLE SCOPE ................................................................................................................................... 36
4.8. CONSTRUCTOR METHOD........................................................................................................................ 36
4.9. OVERLOADING CONSTRUCTORS............................................................................................................. 36
4.10. METHOD OVERLOADING AND OVERRIDING ........................................................................................... 37
4.11. 'IS A', 'HAS A' RELATIONSHIP ................................................................................................................... 40
4.12. VARIABLES ARE SHADOWED AND METHODS ARE OVERRIDDEN ............................................................. 41
4.13. LATE BINDING ........................................................................................................................................ 41
5. COLLECTIONS .......................................................................................................................................... 42
5.1. WHAT IS A COLLECTIONS FRAMEWORK?............................................................................................... 42
5.2. WHAT ARE THE BENEFITS OF A COLLECTIONS FRAMEWORK? ............................................................... 42
5.3. ARE THERE ANY DRAWBACKS?.............................................................................................................. 43
5.4. INTERFACES ........................................................................................................................................... 43
5.5. GENERICS ............................................................................................................................................... 44
5.6. COLLECTION .......................................................................................................................................... 44
5.7. SET ......................................................................................................................................................... 44
5.8. LIST ........................................................................................................................................................ 44
5.9. MAP ....................................................................................................................................................... 45
5.10. OBJECT ORDERING................................................................................................................................. 45
5.11. GENERAL INFO ....................................................................................................................................... 45
6. PROCESS MODELS ................................................................................................................................... 50
6.1. ITERATIVE AND INCREMENTAL DEVELOPMENT ..................................................................................... 50
6.2. EVOLUTIONARY PROTOTYPING .............................................................................................................. 52

Diploma – Object Oriented Programming 1


Accredited Course Provider

6.3. UNIFIED PROCESS .................................................................................................................................. 53

7. TESTING - OBJECT ORIENTED SYSTEM TESTING ....................................................................... 59


7.1. OBJECT CLASS TESTING ........................................................................................................................ 59
7.2. OBJECT INTEGRATION ........................................................................................................................... 59
8. DESIGN PATTERNS ................................................................................................................................. 60
8.1. USES ...................................................................................................................................................... 60
8.2. DOCUMENTATION.................................................................................................................................. 60
8.3. CLASSIFICATION.................................................................................................................................... 61
8.4. CREATIONAL PATTERNS ........................................................................................................................ 61
8.5. STRUCTURAL PATTERNS ........................................................................................................................ 61
8.6. BEHAVIORAL PATTERNS ....................................................................................................................... 61
8.7. DOCUMENTATION OF PATTERNS ........................................................................................................... 62

2 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

1. Introduction

1.1. Computer Program


A computer program is a set of statements or instructions to be used directly or indirectly in a
computer in order to bring about a certain result.

1.1.1. Programming Language

▪ A programming language or computer language is a standardized communication


technique for expressing instructions to a computer.

▪ It is a set of syntactic and semantic rules used to define computer programs

1.1.2. Syntax & Semantics

▪ Refers to the spelling and grammar of a programming language. Computers are


inflexible machines that understand what you type only if you type it in the exact form
that the computer expects. The expected form is called the syntax.

▪ For example, if you misspell a command, it is a syntax error.

▪ If, on the other hand, you enter a legal command that does not make any sense in the
current context, it is a semantic error.

1.2. Program Design Methods


• Unstructured Programming
• Structured Programming
• Modular Programming
• Object Oriented Programming
• Data Oriented Programming

1.2.1. Unstructured Programming


▪ Unstructured programming is a programming paradigm where all code is contained in
a single continuous block.
▪ Unstructured programming languages have to rely on execution flow statements such
as Goto, used in many languages to jump to a specified section of code.

1.2.2. Structured Programming

• A style of programming in which the programmer divides his program's source code
into logically structured chunks of code.
• This is a design approach where complex systems are broken down into smaller,
more manageable pieces
• A program or program module that has one beginning and one ending, and each step
in the program execution consists of one of the following
Sequence (Executing the sequence of instructions one after the other)
Selection (Presentation of a condition and the choice between two actions.)
Repetition (Presentation of set of instructions to be performed rapidly as long as

Diploma – Object Oriented Programming 3


Accredited Course Provider

Condition is true.)

1.2.3. Modular Programming

Modular programming is an advancement of structured programming, in which the whole


program is decomposed into more manageable modules. There no of entry points and exit
points to execute the program.

There are two main principles behind modular program.

1. Coupling - The degree to which one class is connected to relies upon other class.
2. Cohesion - The degree to which the attributes and behaviors of a single class are related
Each other.

By striving for high cohesion and low coupling, we want each class to focus on essentially
one thing and for each class to be as independent as possible. The reason behind the goals
of high cohesion and low coupling is object reusability.

1.2.4. Object Oriented Programming


OOP is a programming paradigm that uses "objects" and their interactions to design
applications and computer programs. It is based on several techniques, including
inheritance, modularity, polymorphism, and encapsulation.

1.2.5. Data Oriented Programming


The main concern is on data structures used on the requirements which are suitable
according to the chosen abstracts. Its fully focusing on abstract data types and their
implementations.

Example: Linked List, Stack …etc

4 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

2. Concepts
Three basic concepts underlining Object Oriented Programming Concepts

• Encapsulation (Data Abstraction)


• Inheritance
• Polymorphism

2.1. Encapsulation
When an object carries out its operations, those operations are hidden. This is the essence
of encapsulation.
Encapsulation is a method which enables you to hide inside the object, both the data fields
and the methods that act on that data.

Encapsulation is also referred to as “Information Hiding”.

In an object, encapsulated data members are,


• Global to object’s methods
• Local to the objects

Encapsulation is achieved by using modifiers. Modifiers are language keywords that modify
the definition of a class, method or a variable.

2.2. Modifiers
Modifiers fall into two categories:
Access modifiers: public, protected, private.
Non-access modifiers (including strictfp, final, and abstract).

2.2.1. Access Modifiers


There are four levels of access but only three access modifiers

Access modifiers: public, private, protected

The fourth access level (default) is what you get when no access modifier is used.

A class can be declared with only public or default access

Methods and instance (nonlocal) variables are called members, and members can use all
four access levels: public, protected, default and public

Class visibility revolves around whether code in one class can:


Create an instance of another
Extend or subclass another
Access methods and variables of another class.

If a class cannot be accessed its members cannot be accessed.

Diploma – Object Oriented Programming 5


Accredited Course Provider

Default Level Access


There is no actual keyword for declaring default access modifier. It is applied by default in the
absence of an access modifier. A class with default access can be seen only by class within
the same package.

long length; //attributes

void getlength() { //methods


return length;
}

Notice that neither the member variable nor the method supplies an access modifier. So they
take on the default access modifier implicitly.

Look at the following source file:


package cert;
class Beverage { }

Now look at the second source file:


package exam.stuff;
import cert.Beverage;
class Tea extends Beverage { }

The superclass (Beverage) is in a different package from the subclass (Tea). The import
statement at the top of the Tea file is trying to import the Beverage class. The Beverage file
compiles fine, but Tea, it will not compile because its superclass, Beverage, has default
access and is in a different package.

Default members can be accessed only by other classes in the same package

Example

6 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Public level access


Class:
A class declaration with a public keyword gives all classes from all packages access to the
public class.

If the public class is to be use is in different package from the class you are writing, you still
need to import the public class.

Members
public members can be accessed by all classes, even in different packages

public int count;


public boolean isActive;

Example

Private Level Access


Private members can only be accessed by code in the same class.
Private members are not visible to subclasses, so private members cannot be inherited.

private String firstname;


private double howBigIsIt;

Diploma – Object Oriented Programming 7


Accredited Course Provider

Example

Protected Level Access


Default and protected members differ only in when subclasses are involved. Protected
members can be accessed by other classes in the same package plus subclasses
regardless of package.

protected = package + kids (kids meaning subclasses)

A subclass outside the package cannot access a member through a reference variable.

A protected member is accessible by all classes in the same package and subclasses of
other packages.

For a subclass outside the package, the protected member can be accessed only through
inheritance.

8 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Example - Accessing protected members through references:

Visibility
Visibility Public Protected Default Private

From the same class Yes Yes Yes Yes


From any class in the same package Yes Yes Yes No
From any non-subclass class outside Yes No No No
the package
From a subclass in the same package Yes Yes Yes No
From a subclass outside the same Yes Yes No No
package

2.2.2. Non-Access Modifiers


Some of the non-access modifiers include the following:

Abstract modifier
There are situations where you need to define a class which declares the structure of a given
abstraction without providing a complete implementation of every method. You can declare
that certain methods are required to be overridden by subclasses using the abstract type
modifier.

Any class which contains any methods declared abstract must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class keyword at
the beginning of the class declaration. Such classes cannot be directly instantiated with the
new operator since their complete implementation is undefined.

You cannot declare abstract constructors, or abstract static methods. Any subclass of an
abstract class must either implement all of the abstract methods in the super class, or be
itself declared abstract.

Diploma – Object Oriented Programming 9


Accredited Course Provider

Final modifier
Can be considered as a constant. All methods and instance variables may be overridden by
default. If you wish to declare that you want to no longer allow subclasses to override your
variables or methods, you can declare them final.

A Final class cannot be subclassed

Attempting to subclass a final class will result in a compiler error.

You should make a final class only if you need an absolute guarantee that none of the
methods in that class will ever be overridden. If you're deeply dependent on the
implementations of certain methods, then using final gives you the security that nobody can
change the implementation.

You'll notice many classes in the Java core libraries are final. For example, the String class
cannot be subclassed.

Final methods cannot be overridden in a subclass

You can't mark a class as both abstract and final. They have nearly opposite meanings. An
abstract class must be subclassed, whereas a final class must not be subclassed.

Synchronized modifier

• A synchronized keyword indicates that a method can be accessed by only one thread
at a time.
• synchronized modifier applies only to methods
• synchronized methods can have any access control and can also be marked final
• synchronized methods cannot be abstract

Static modifier

• The static modifier specifies that a variable or method is the same for all objects of a
particular class. When a variable is declared as being static, it is only allocated once
regardless of how many objects are instantiated. (Typically new variables are
allocated for each instance of a class)

10 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

• All instantiated objects share the same instances of the static variable. When you
declare a method static, it is not instantiated with each object, but is part of the entire
class. Therefore you invoke the method by preceding it with the class name.
• If a method behavior is not dependent on the instance variable values of the object
and is to behave is the same manner always the method is marked static.

• Static members are not tied to any particular instance of a class.

• An instance of a class does not need to exist in order to use a static member of a
class.

• There is only one copy of the static variable per class and all instances share it.

• Static variables get the same default value as instance variables.

• A static method (such as main( ) ) cannot access a nonstatic (instance) variable.

• Static members exists before you create an instance of a class.

Example

2.2.3. Different types of Modifiers

Class Modifiers
Modifier Meaning
Public Accessible from all other classes
Abstract Class cannot be instantiated
Final No sub classes can be created

Diploma – Object Oriented Programming 11


Accredited Course Provider

Constructor Modifiers
Modifier Meaning
public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class

Field Modifiers
Modifier Meaning
public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class
Static Only a Single value for all instances
Transient It is not part of the persistent state of an object
Final It is a Constant

Method Modifiers
Modifier Meaning
Public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class
Static Bound to class itself, not to any instance
Final No subclass can override it.
Native Implemented in another programming language
synchronised Must be locked before a thread can invoke it.
Abstract No method Body, extended class should implement it

2.3. Inheritance
2.3.1. Super class and Subclass
Using inheritance you can create a general class that trait comments to related items. This
class then can be inherited by the other more specific classes each adding things unique to
it.
A class that is inherited is called a super class. The class that does the inheritance is called
the subclass. Therefore a subclass is a specialized version of a super class. It inherits all of
the instance variables and methods defined by the super class, and add its own unique
elements.
E.g.

Generalized Bicycle Super Class

Racing Bicycle Mountain Bicycle Subclass

12 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Specialized

A subclass is a class that inherits attributes and methods from superclass.

Diploma – Object Oriented Programming 13


Accredited Course Provider

2.3.2. Implementing Inheritance in Java

The extends keyword is used to derive a class from a superclass.

Example

2.4. Polymorphism
Combines Greek Words Poly, Morphism. Poly: Many and Morphism: Forms.

The quality of having more than one form. In the context of Object Oriented Programming,
polymorphism refers to the fact a single operation can have different behavior in different
objects.

Sometimes an operation has the same name in


different classes. You can open a door, you can
open a window, or you can open a news paper. In
each case you are performing a different operation.
In OO each class “knows” how that operation is
supposed to take place. This is called polymorphism.

14 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

2.5. Interfaces
2.5.1. What Is an Interface?
An interface defines a protocol of behavior that can be implemented by any class anywhere
in the class hierarchy. An interface defines a set of methods but does not implement them. A
class that implements the interface agrees to implement all the methods defined in the
interface, thereby agreeing to certain behavior.

Definition: An interface is a named collection of method definitions (without


implementations). An interface can also declare constants.

Because an interface is simply a list of unimplemented, and therefore abstract, methods, you
might wonder how an interface differs from an abstract class. The differences are significant.

▪ An interface cannot implement any methods, whereas an abstract class can.


▪ A class can implement many interfaces but can have only one superclass.
▪ An interface is not part of the class hierarchy. Unrelated classes can implement the
same interface.

Suppose that you have written a class that can watch stock prices coming over a data feed.
This class allows other classes to register to be notified when the value of a particular stock
changes. First, the class, which we'll call StockMonitor, would implement a method that
lets other objects register for notification:

public class StockMonitor {


public void watchStock(StockWatcher watcher, String tickerSymbol, double delta)
{
}
}

The watchStock method ensures, through the data type of its first argument, that all
registered objects implement the valueChanged method. It makes sense to use an
interface data type here because it matters only that registrants implement a particular
method. If StockMonitor had used a class name as the data type, which would artificially
force a class relationship on its users. Because a class can have only one superclass, it
would also limit what type of objects can use this service.

2.5.2. Defining an Interface


public interface StockWatcher
{
final String sunTicker = "SUNW";
final String oracleTicker = "ORCL";
final String ciscoTicker = "CSCO";
void valueChanged(String tickerSymbol, double newValue);
}

This interface defines three constants, which are the ticker symbols of watchable stocks. This
interface also declares, but does not implement, the valueChanged method. Classes that
implement this interface provide the implementation for that method.

Diploma – Object Oriented Programming 15


Accredited Course Provider

2.5.3. The Interface Declaration


The following figure shows all possible components of an interface declaration.

Public Interface InterfaceName Extends SuperInterfaces


{
//Interface Body
}

2.5.4. The Interface Body


The interface body contains method declarations for all the methods included in the interface.
A method declaration within an interface is followed by a semicolon (;) because an interface
does not provide implementations for the methods declared within it.

All methods declared in an interface are implicitly public and abstract.

An interface can contain constant declarations in addition to method declarations. All


constant values defined in an interface are implicitly public, static, and final.

Member declarations in an interface disallow the use of some declaration modifiers; you
cannot use transient, volatile, or synchronized in a member declaration in an
interface. Also, you may not use the private and protected specifiers when declaring
members of an interface.

2.5.5. Implementing an Interface


An interface defines a protocol of behavior. A class that implements an interface adheres to
the protocol defined by that interface. To declare a class that implements an interface,
include an implements clause in the class declaration. Your class can implement more
than one interface (the Java platform supports multiple inheritance for interfaces), so the
implements keyword is followed by a comma-separated list of the interfaces implemented
by the class.

By Convention: The implements clause follows the extends clause, if it exists.

Here's a partial example that implements the StockWatcher interface:

16 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

When a class implements an interface, it is essentially signing a contract. Either the class
must implement all the methods declared in the interface and its superinterfaces, or the class
must be declared abstract. The method signature--the name and the number and type of
arguments in the class--must match the method signature as it appears in the interface. The
StockApplet implements the StockWatcher interface, so the applet provides an
implementation for the valueChanged method. The method ostensibly updates the applets
display or otherwise uses this information.

2.6. Packages
Java provides a large number of classes. A package organizes there classes into groups.
The lang package is one of the most important packages in Java. All classes in this package
can be used in your program with out explicit importing.

2.6.1. Importing a Package Member


To import a specific member into the current file, put an import statement at the beginning of
your file before any class or interface definitions but after the package statement, if there is
one. Here's how you would import the Circle class from the graphics package created in
the previous section:
import graphics.Circle;

Now you can refer to the Circle class by its simple name:

Circle myCircle = new Circle();

This approach works well if you use just a few members from the graphics package. But if
you use many classes and interfaces from a package, you can import the entire package.

2.6.2. Importing an Entire Package


To import all the classes and interfaces contained in a particular package, use the import
statement with the asterisk (*) wildcard character:

import graphics.*;

Now you can refer to any class or interface in the graphics package by its short name:

Diploma – Object Oriented Programming 17


Accredited Course Provider

Circle myCircle = new Circle();


Rectangle myRectangle = new Rectangle();

The asterisk in the import statement can be used only to specify all the classes within a
package, as shown here. It cannot be used to match a subset of the classes in a package.
For example, the following does not match all the classes in the graphics package that
begin with A:

import graphics.A*; // does not work

Instead, it generates a compiler error. With the import statement, you can import only a
single package member or an entire package.
For your convenience, the Java runtime system automatically imports three entire packages:

• The default package (the package with no name)


• The java.lang package

18 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

3. Introduction to Unified Modeling Language (UML)

3.1. History of the UML


During the 1990s many different methodologies, along with their own set of notations, were
introduced to the Market. Three popular ones are OMT, Booch, and OOSE (Jacobson). OMT
was strong in analysis and weaker in the design area. Booch 1991 was strong in design and
weaker in analysis. Jacobson was strong in behavior analysis and weaker in the other areas.

The use of different notations brought confusion to the market since one symbol meant
different things to different people. To resolve this confusion Unified Modeling Language
(UML) was introduced.

“UML is a language used to specify, visualize, and document the artifacts of an object-
oriented system under development. It represents the unification of the Booch, OMT, and
Objector notations, as well as the best ideas from a number of other methodologies”.

UML is an attempt to standardize the artifacts of analysis and design: semantic models,
syntactic notation, and diagrams.

In November 1997, the UML was adopted as the standard modeling language by the
Object Management Group (OMG).

3.2. Brief overview of UML


The Unified Modeling Language (UML) is a standard language for writing software blueprints.
The UML may be used to visualize, specify, construct and document the artifacts of a
software-intensive system.

The UML is only a language and so is just one part of a software development method.
The UML is process independent, although optimally it should be used in a process that is
use case driven, architecture-centric, iterative, and incremental.

UML is a general-purpose visual modeling language that is used to specify, visualize,


construct and document the artifacts of a software system

3.2.1. UML is a language


It provides a vocabulary and the rules of combining words in that vocabulary for the purpose
of communicating the conceptual and physical representation of a system

3.2.2. UML for visualization

It is a graphical language and has graphical symbols. Each symbol has well defined
semantics

3.2.3. UML for specification


By building models which are precise, unambiguous and complete, all decisions for analysis,
design and implementation for development and deployment of software intensive systems
are addressed

Diploma – Object Oriented Programming 19


Accredited Course Provider

3.2.4. UML for construction


It is not a visual programming language and its models can be connected directly to a variety
of programming languages. Reverse engineering is possible

3.2.5. UML for documentation


Documentation of system’s architecture is performed in detail. It provides a language for
expressing requirements and tests and modeling the activities of project planning and
release management

3.3. Conceptual Model of UML


To understand the UML, you need to form a conceptual model of the language, and this
requires leaning these major elements: the UML’s basic building blocks, the rules that dictate
how those building blocks may be put together, and some common mechanisms that apply
throughout the UML.

The vocabulary of the UML encompasses three kinds of building blocks:

1. Things
2. Relationships
3. Diagrams

Things are the abstractions that are first-class citizens in a model; relationships tie these
things together; diagrams group interesting collections of things.

3.4. Diagrams in UML 1.5 Version


A diagram is the graphical presentation of a set of elements, most often rendered as a
connected graph of vertices (things) and archs (relationships).
UML Includes nine diagrams:

• A Class Diagram shows a set of classes, interfaces, and collaborations and their
relationships.
• An Object Diagram shows a set of objects and their relationships.
• A Use Case Diagram shows a set of use cases and actors (a special kind of class)
and their relationships.
• Both Sequence Diagrams and Collaboration Diagrams are kinds of Interaction
Diagrams.
• A Statechart Diagram shows a state machine, consisting of states, transitions,
events, and activities. Statechart diagrams address the dynamic view of a system.
• An Activity Diagram is a special kind of a statechart diagram that shows the flow
from activity to activity within a system.
• A Component Diagram shows the organization and dependencies among a set of
components. These diagrams address the static implementation view of a system.
• A Deployment Diagram shows the configuration of run-time processing nodes and
the components that live on them. These diagrams address the static deployment
view of architecture.

20 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

3.5. Use case diagrams

Use Case diagrams show the interactions between use cases and actors. Use cases
represent system functionality, the requirements of the system from the user's perspective.
That is, the actions that the system performs to generate results requested by the actor of
the system.
Actors represent the people or systems that provide or receive information from the system;
they are among the stakeholders of a system. That is they can be either “External entities
that interact with the system” or “A role that a user plays with respect to the system”.
Use Case diagrams, therefore, show which actors initiate use cases; they also illustrate that
an actor receives information from a use case. In essence, a Use Case diagram can illustrate
the requirements of the system.

Notations

Actor UseCase

Use Case Relationships (Discussion)

Consists of TWO kinds of relationships


1. Relationships between actors and use cases
2. Relationships between use cases
a. Include
b. Extends
c. Generalization

Diploma – Object Oriented Programming 21


Accredited Course Provider

Use Case diagram for an Automated Teller Machine (ATM) system

Transfer Funds

Customer
Deposit Funds

Make Payment Credit System


View Balance
Withdraw Money

Change Pin Bank Officer

The above Use Case diagram shows the interactions between the use cases and actors of
an ATM system. In this example, the bank's customer initiates a number of use cases:
Withdraw Money, Deposit Funds, Transfer Funds, Make Payment, View Balance, and
Change PIN. A few of the relationships are worthy of further mention. The bank officer can
also initiate the Change PIN use case. The Make Payment use case shows an arrow going
to the credit system. External systems may be actors and, in this case, the credit system is
shown as an actor because it is external to the ATM system. The arrow going from a use
case to an actor illustrates that the use case produces some information that an actor uses.
In this case, the Make Payment use case provides credit card payment information to the
credit system.
Much information can be gleaned from viewing Use Case diagrams. This one diagram shows
the overall functionality of the system. Users, project managers, analysts, developers, quality
assurance engineers, and anyone else interested in the system as a whole can view these
diagrams and understand what the system is supposed to accomplish.

22 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

3.5.1. Use Case Specification / Description

Use case can be described using the following information


1. Use Case Name
2. Actor(s)
3. Description (High Level)
4. Normal Flow of Events
5. Alternate Flow of Events
6. Pre-Conditions
7. Post-Conditions
8. Assumptions

Sample Question for Discussion

An online retails company wishes to implement a Web-based marketing system with facilities
to aid their purchasing and stock control. The outline requirements for the systems are as
follows:
All customers must be registered with the system. There should be a screen that allows them
to do this on a fill-in-the-form basis. If they fill in all the details required and a valid e-mail
address they will be issued with a customer registration number. Registered customers may
purchase online. Typically they will browse through details of the goods available and select
one or more items. If an item is out of stock it will not be displayed whilst a customer is
browsing. When they have selected all the items they require they can then move to a screen
which enables them to enter their customer number and complete the purchase. Once
ordered, goods are sent to a customer by a dispatcher. Every morning the dispatcher
requests a list of goods that are to be sent out. The list contains the names and addresses of
all the customers who have made an order on the previous day and the items they have
ordered. A buyer determines the range of items that are for sale. A buyer can add new items
to the online catalogue and discontinue the sale of existing items. Each morning the buyer
requests the list of those items for which the quantity in stock is lower than their re-order
level. Items on the list are re-ordered. When new stocks arrive they are received by a
warehouseman who records the new stock levels on the computer system.
a) Draw a use case diagram for this system.
b) Develop a use case description of the way a customer orders goods. Your answer should
show a normal sequence and also list some alternate sequences.

3.6. Class diagrams

Class diagrams are the most important model in UML that illustrates the structure of the
system. They represent the static view of the system. Class diagrams show the interactions
between classes in the system. Classes can be seen as the blueprint for objects, as we'll
discuss later. An account, for example, is an object. An account is a blueprint for checking
account of a customer therefore an account is a class. Classes contain information and
behavior that acts on that information. The Account class contains the customer's PIN and
behavior to check the PIN. A class on a Class diagram is created for each type of object in a

Diploma – Object Oriented Programming 23


Accredited Course Provider

Sequence or Collaboration diagram. The following are the notations for representing a class
in UML:

Notation Example

Class Name Student


Attributes Name
Address

Operations Add_student
Delete_student

The Class diagram for the system's Withdraw Money use case is illustrated below:

The Class diagram above shows the relationships between the classes that implement the
Withdraw Money use case. This is done with four classes: Card Reader, Account, ATM
Screen, and Cash Dispenser. Each class on a Class diagram is represented by a rectangle
divided into three sections. The first section shows the class name. The second section
shows the attributes the class contains. An attribute is a piece of information that is
associated with a class. For example, the Account class contains three attributes: Account
Number, PIN, and Balance. The last section contains the operations of the class. An
operation is some behavior that the class will provide. The Account class contains four
operations: Open, Withdraw Funds, Deduct Funds, and Verify Funds.
The lines connecting classes show the communication relationships between the classes.
For instance, the Account class is connected with the ATM Screen class because the two

24 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

directly communicate with each other. The Card Reader is not connected to the Cash
Dispenser because the two do not communicate.
Developers use Class diagrams to actually develop the classes. Tools such as Rose
generate skeletal code for classes, and then developers flesh out the details in the language
of their choice. Analysts use Class diagrams to show the details of the system. Architects
also look at Class diagrams to see the design of the system. If one class contains too much
functionality, an architect can see this in the Class diagram and split out the functionality into
multiple classes. Should no relationship exist between classes that communicate with each
other, an architect or developer can see this too. Class diagrams should be created to show
the classes that work together in each use case, and comprehensive diagrams containing
whole systems or subsystems can be created as well.

3.7. Packages and Object Diagrams


To simplify complex class diagrams, you can group classes into packages. A package is a
collection of logically related UML elements. The diagram below is a business model in which
the classes are grouped into packages.

Packages appear as rectangles with small tabs at the top. The package name is on the tab
or inside the rectangle. The dotted arrows are dependencies. One package depends on
another if changes in the other could possibly force changes in the first.

Object diagrams show instances instead of classes. They are useful for explaining small
pieces with complicated relationships, especially recursive relationships.

This small class diagram shows that a university Department can contain lots of other
Departments.

Diploma – Object Oriented Programming 25


Accredited Course Provider

The object diagram below instantiates the class diagram, replacing it by a concrete example.

Each rectangle in the object diagram corresponds to a single instance. Instance names are
underlined in UML diagrams. Class or instance names may be omitted from object diagrams
as long as the diagram meaning is still clear.

Sample Question for Discussion


A sports club has members who only make use of the gymnasium and those who also play
a racquet game such as tennis. The latter are charged an extra 10 per cent on their annual
fee. All members have their name, membership number, address and the annual fee
payable recorded. If applicable the name of the racquet game played is also recorded.
From time to time the club secretary requires a display of the details held on each member,
irrespective of whether they use only the gymnasium or also play a racquet game. The
UML class diagram given below has been proposed as part of an object oriented design of
a software system to help the club maintain its membership details. The intent of the
designer is that a SportsClub object receiving the message displayMembers can make use
of the display operation of its GymnMember and RacquetsMember associates. They
display the relevant attributes of a GymnMember and RacquetsMember respectively.
Redraw the diagram making at least THREE major changes to improve its design.

26 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

3.8. Sequence Diagrams


Class and object diagrams are static model views. Interaction diagrams are dynamic. They
describe how objects collaborate. A sequence diagram is an interaction diagram that details
how operations are carried out, what messages are sent and when. Sequence diagrams are
organized according to time. The time progresses as you go down the page. The objects
involved in the operation are listed from left to right according to when they take part in the
message sequence. They are used to show the flow functionality through a use case. For
example, the Withdraw Money use case has several possible sequences, such as
withdrawing money, attempting to withdraw without available funds, attempting to withdraw
with the wrong PIN, and several others. The normal scenario of withdrawing without any
problems such as entering the wrong PIN or insufficient funds in the account is shown below:

Sequence diagram for cash withdrawal from an ATM

CardReader ATM Screen Account Cash


: Customer Dispenser
1.AcceptCard
2.ReadCardNo.

3. Initialize Screen

4. Open Account
5. Prompt for Pin

6. Enter Pin 7. Verify Pin

8. Prompt for Transaction


9. Select Transaction(Withdraw)

10. Prompt for Amount

11.Enter Amount
12. Withdraw Fund
13. Verify Fund

14.Deduct Funds

15. Provide Cash


16. Provide Receipt
17. Eject Card

This Sequence diagram shows the flow of processing through the Withdraw Money use
case. Any actors involved are shown at the top of the diagram; the customer actor is shown
in the above example. The objects that the system needs in order to perform the Withdraw
Money use case are also shown at the top of the diagram. Each arrow represents a message
passed between actor and object or object and object to perform the needed functionality.
One other note about Sequence diagrams is that they display objects, not classes. Classes

Diploma – Object Oriented Programming 27


Accredited Course Provider

represent types of objects; Objects are specific that is instead of just customer the Sequence
diagram can show John (Customer Name).
The use case starts with the customer inserting his card into the card reader, an object
indicated by the rectangle at the top of the diagram. Then, the card reader reads the card
number, opens the account object, and initializes the ATM screen. The screen prompts
customer for PIN. Customer enters the Pin. The screen verifies the PIN with the account
object and they match. The screen presents customer with the options, and customer
chooses withdraw. The screen then prompts the customer for the amount to withdraw.
Customer enters amount. Then, the screen withdraws the funds from the account. This
initiates a series of processes that the account object performs. First, customer’s account
verifies that the account contains at least the requested amount. Then, it deducts the funds
from the account. Next, it instructs the cash dispenser to provide the required amount in
cash. Customer’s account also instructs the dispenser to provide a receipt. Lastly, it instructs
the card reader to eject the card.
This Sequence diagram illustrated the entire flow of processing for the Withdraw Money use
case by showing a specific example of customer withdrawing cash from the account. Users
can look at these diagrams to see the specifics of their business processing. Analysts see
the flow of processing in the Sequence diagrams.
Developers see objects that need to be developed and operations for those objects. Quality
assurance engineers can see the details of the process and develop test cases based on the
processing. Sequence diagrams are therefore useful for all stakeholders in the project.

3.9. Collaboration Diagram


Collaboration diagrams are also interaction diagrams. They convey the same information
as sequence diagrams, but they focus on object roles instead of the times that messages are
sent. In a sequence diagram, object roles are the vertices and messages are the connecting
links.
However, Collaboration diagrams show this information in a different way and with a different
purpose. The Sequence diagram illustrated above is shown in below as a Collaboration
diagram.
Collaboration diagram for cash withdrawal from an ATM

13: Verify Fund


14: Deduct Funds

6: Enter Pin
9: Select Transaction(Withdraw) 7: Verify Pin
11: Enter Amount 12: Withdraw Fund
ATM Account
Screen
5: Prompt for Pin
: Customer 8: Prompt for Transaction
10: Prompt for Amount
15: Provide Cash
16: Provide Receipt

4: Open Account
3: Initialize Screen
1: AcceptCard

Cash
17: Eject Card Dispenser

2: ReadCardNo.

CardReader
28 Diploma – Object Oriented Programming
[Type text]
Accredited Course Provider

In this Collaboration diagram, the objects are represented as rectangles and the actors are
stick figures, as before. Whereas the Sequence diagram illustrates the objects and actor
interactions over time, the Collaboration diagram shows the objects and actor interactions
without reference to time. For example, in this diagram, we see that the card reader instructs
customer's account to open and customer’s account instructs the card reader to eject the
card. Also, objects that directly communicate with each other are shown with lines drawn
between them. If the ATM screen and cash dispenser directly communicated with one
another, a line would be drawn between them. The absence of a line means that no
communication occurs directly between those two objects.

Collaboration diagrams, therefore, show the same information as Sequence diagrams, but
people look at Collaboration diagrams for different reasons. Quality assurance engineers and
system architects look at these to see the distribution of processing between objects.
Suppose that the Collaboration diagram was shaped like a star, with several objects
communicating with a central object. A system architect may conclude that the system is too
dependent on the central object and redesign the objects to distribute the processing power
more evenly. This type of interaction would have been difficult to see in a Sequence diagram.

3.10. State chart Diagrams


Statechart diagrams provide a way to model the various states in which an object can exist.
While the Class diagrams show a static picture of the classes and their relationships,
Statechart diagrams are used to model the more dynamic behavior of a system. These types
of diagrams are extensively used in building real-time systems.
A Statechart diagram shows the behavior of an object. For example, a bank account can
exist in several different states. It can be open, closed, or overdrawn. An account may
behave differently when it is in each of these states. Statechart diagrams are used to show
this information. The diagram below shows an example of a Statechart diagram for a bank
account.
Statechart diagram for the Account class

Withdraw( Balance < 0 )

Open

OverDrawn
Do: Send Notice To Customer
Deposit( Balance < 0 )
Customer Request Closure

Closed
Check Balance( Balance < 0 for > 30 Days )

In this diagram, we can see the states in which an account can exist. We can also see how
an account moves from one state to another. For example, when an account is open and the
customer requests the account's closure, the account moves to the closed state. The

Diploma – Object Oriented Programming 29


Accredited Course Provider

customer's request is called the event and the event is what causes a transition from one
state to another.
If the account is open and the customer makes a withdrawal, the account may move to the
overdrawn state. This will only happen if the balance of the account is less than zero. We
show this by placing [Balance < 0] on the diagram. A condition enclosed in square brackets
is called a guard condition, and controls when a transition can or cannot occur.
There are two special states that is the start state and the stop state. The start state is
represented by a black dot on the diagram, and indicates what state the object is in when it is
first created. The stop state is represented by a bull’s-eye, and shows what state the object is
in just before it is destroyed. On a Statechart diagram, there is one and only one start state.
On the other hand, you can have no stop state, or there can be as many stop states as you
need.
Certain things may happen when the object is inside a particular state. In our example, when
an account is overdrawn, a notice is sent to the customer. Processes that occur while an
object is in a certain state are called actions.
Statechart diagrams aren't created for every class; they are used only for very complex
classes. If an object of the class can exist in several states, and behaves very differently in
each of the states, you may want to create a Statechart diagram for it. Many projects won't
need these diagrams at all. If they are created, developers will use them when developing
the classes.
Statechart diagrams are created for documentation only. For Example: When you generate
code from your Rational Rose model, no code will be generated from the information on the
Statechart diagrams.

3.11. Activity Diagrams


Activity diagrams illustrate the flow of functionality in a system. They may be used in
business modeling to show the business workflow. They may be used in requirements
gathering to illustrate the flow of events through a use case. These diagrams define where
the workflow starts, where it ends, what activities occur during the workflow, and in what
order the activities occur. An activity is a task that is performed during the workflow. The
structure of an activity diagram is similar to a Statechart diagram because activities are the
state of doing something. An example of an activity diagram is shown below. The activities in
the diagram are represented by rounded rectangles. These are the steps that occur as you
progress through the workflow. Objects that are affected by the workflow are represented by
squares. There is a start state, which represents the beginning of the workflow, and an end
state, which represents the end. Decision points are represented by diamonds.
Activity diagrams can show activities that are conditional and/or parallel. Activity diagrams
are also useful for analyzing use case by describing what actions need to take place and
when they should occur. These diagrams are read from top to bottom and have “Branches”
and “Forks” to describe conditional and parallel behaviour. A Fork is used when multiple
activities are occurring at the same and a “Join” indicates the end of a fork. The Branch
indicates what activities will take place based on a set of conditions and a “Merge” indicates
the end of a branch.
The three involved classes (people, etc.) of the activity are Customer Service
Representative, Credit Department Manager and Customer. The process begins at the
black start circle at the top and ends at the concentric white/black stop circles at the bottom.
The activities are rounded rectangles. The solid lines, known as transitions, show how one
activity leads to another in the process. If needed, you can place greater detail on the
transitions, describing the circumstances under which the transition may or may not occur
and what actions will be taken during the transition.

30 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

The activity diagram may be divided into vertical swimlanes. Each swimlane represents a
different role within the workflow. By looking at the activities within a given swimlane, you can
find out the responsibility of that role. By looking at the transitions between activities in
different swimlanes, you can find out who needs to communicate with whom. All of this is
very valuable information when trying to model or understand the business process. Activity
diagrams do not need to be created for every workflow, but they are powerful communication
tools, especially with large and complex workflows.
A transition may branch into two or more mutually exclusive transitions. Guard expressions
(inside [ ]) label the transitions coming out of a branch. A branch and its subsequent merge
marking the end of the branch appear in the diagram as hollow diamonds.
A transition may fork into two or more parallel activities. The fork and the subsequent join of
the threads coming out of the fork appear in the diagram as solid bars.

Activity diagram for opening an account

Credit Service Credit Department Manager Customer


Representative
Customer Serv ice Representativ e Credit Department Manager Customer

Collect Customer
Information

Set Credit Limit


Create New
Credit Account Do / Check Customer Credit History

[ Meets Criteria ]
[ Doesn't Meet Criteria ]
Review Credit History

Reject Account Approve


Account

Approved Accept Credit


Terms

Open Account

Sign Paperwork

Issue Pass
Book

Diploma – Object Oriented Programming 31


Accredited Course Provider

3.12. Component and Deployment Diagrams


Physical diagrams are used when the development of the system is complete. These
diagrams are used to give descriptions of the physical information about a system. There are
two types of physical diagrams in UML
1. Component Diagram
2. Deployment Diagram
Component diagrams show the software components of a system and how they are related
to each other; these relationships are called “Dependencies”. Deployment diagrams show
the physical relationship between hardware and software in a system.

When drawing physical diagrams both the deployment and the component diagrams are
combined into one physical diagram.
The deployment diagram contains nodes and connections where a node usually represents a
piece of hardware in the system and a connection depicts the communication path used by
the hardware to communicate which usually indicates a method such as TCP/IP.
The component diagram contains components and dependencies where components
represent the physical packaging of a module of code and the dependencies between
components show how changes made to one component may affect the other components in
the system.
Component diagrams can also show the interfaces used by the components to communicate
with each other.

Notations Example

Component
Node Registration Server

32 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

4. Object Oriented Programming Concepts


4.1. What is an Object?
A ‘thing’ may have a physical presence such as a ‘table’ ,‘chair’ or an abstract concept such
as ‘a job’, ’course’. An object is an abstract representation of a ‘thing’ in the real world. We
simulate a problem domain in the real-world through objects. An object has a unique identity,
attributes (What it knows or data about it), and behavior (What it can do).

▪ An Employee object (say employee1) will have the


following attributes (what it knows):
▪ name, age, salary
▪ It will have the following behaviors (what it can do):
▪ set salary, get salary, set name, set age

4.2. What is a Class?


Objects are the representation of things in the real-world.
Classes are templates for objects. They contain all the common properties and behaviors of
a group of objects.

All objects with the same attributes and behaviors belongs to the same class.
Practical Example of a class

Diploma – Object Oriented Programming 33


Accredited Course Provider

4.2.1. Creating Objects


Objects are created by instantiating classes. To use a class in a program, you must first
create an instance of it. Objects of a class can be created using the new operator.

Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and the methods within that object. A software object that modeled your real-world
bicycle would have variables that indicated the bicycle's current state: Its speed is 18 mph, its
pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are formally
known as instance variables because they contain the state for a particular bicycle object,
and in object-oriented terminology, a particular object is called an instance. The above figure
illustrates a bicycle modeled as a software object.

4.3. Instance variables.


Variables are considered instance variables if they are declared outside the methods
definition and not modified by the static keyword.

Example

4.4. Class variables


Class variables apply to classes as a whole, rather than stored individually in objects of the
classes. Class variables help to keep track of class wide information among a set of objects.
static keyword is used in the class variable declaration.
E.g. static int sum;

34 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

4.5. Local variables


Local variables are variables that are declared within a method. The variables scope is only
with in the method. i.e. once the method ends the variable can no longer be referenced.
E.g.
public static void main (String args[])
{
Int num =10; //local variable
// rest of the code
}

4.6. Creating methods

4.6.1. Defining methods


Method’s definitions have 4 basic parts.
• Name of the method
• A list of parameters
• A type of the object or primitive type referenced by the object
• A body of the method
Basic method looks like
Return type methodName (argument list)
{
// body of the method
}

The return type is the primitive type or class of the value returned by the method. It can be of
the primitive type, a class name or void if the method does not return a value at all.
Void displayName() – no return type
Int calucualteSum() – returns a int value
Methods parameter list is a set of variable declarations, separated by commas inside
parenthesis. These parameters become local variables in the body of the method.

Example

class Camera
{
Void clickButton()
{
// this method does not take any arguments
// returns no value
}
int CountPhotographs() {
//no arguments
//return int value
}
boolean changeShutterSpped(int noofMiiliSeconds) {
// this method takes a parameter int data type
// returns a Boolean variable true/false
}
}

Diploma – Object Oriented Programming 35


Accredited Course Provider

4.7. Variable scope


One of the things you must know when using a variable is its scope. Scope is the part of the
program in which variable or other information can be used when the part defining the scope
has completed execution the variable creases to exist.

A variable with a local scope, can be used only inside the block in which it was defined.
Instance variables have a scope that extends to the entire class, so they can be used by any
of the instance methods with in that class.

4.8. Constructor Method


These methods are used to initialize objects. They have the same name as the class and
have no return type. These methods are called automatically when the new operator is
used to allocate memory for an object.

public class twoDPoint {


float x,y;

//constructor definition
twoDPoint(){
x= y = 0;
}
}

No argument Constructor

4.9. Overloading Constructors


A class can have multiple Constructors (Overloaded Constructors). All carries the same
name. They have either different number of arguments or different types of arguments.

4.9.1. this keyword

this keyword is used to refer to the current object. It can be used to,
▪ refer to the current objects member variables,
▪ refer to current objects methods
▪ pass a reference to the current object to a method
▪ return a reference current object

t=this.x; Refers to the member


this.myMethod(this); variable x in this object
return this;

Call the myMethod defined in this class


Return this Object and pass its this Object

36 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

4.9.2. super keyword

This keyword is used to refer to the Super or parent class


super(); Invokes super class Constructor

super(x,y);
super(x,y);
super.m(); Invokes super class Constructor
with x and y arguments
super.m();
Calls the super class method
called m()

4.10. Method Overloading and Overriding

4.10.1. Overloading Methods


In Java it is possible to define two or more methods within the same class that share the
same name, as long as the parameter declarations are different.

The methods are said to be overloaded and the process is related to as ‘method
overloading’. When an overloaded method is involved, java uses the type and or numbers of
arguments as its guide to determine which version of the overloaded method to actually call.
Thus overloaded methods should differ in type and/or number of their parameters. Difference
in argument type alone is insufficient.

Example – Method Overloading

Diploma – Object Oriented Programming 37


Accredited Course Provider

• If two (or more) methods of a class (whether both declared in the same class, or both
inherited by a class, or one declared and one inherited) have the same name but
different signatures, then the method name is said to be overloaded.
• The signature of a method consists of the name of the method and the number and
types of formal parameters in particular order. A class must not declare two methods
with the same signature, or a compile-time error occurs.
• Only the method name is reused in overloading, so method overloading is actually
method name overloading.
• Overloaded methods may have arguments with different types and order of the
arguments may be different.
• Overloaded methods are not required to have the same return type or the list of
thrown exceptions.
• Overloading is particularly used while implementing several methods that implement
similar behavior but for different data types.
• Overloaded methods are independent methods of a class and can call each other just
like any other method.

4.10.2. Constructor Overloading

• Constructors can also be overloaded in similar fashion, as they are also methods.
• Java has some classes with overloaded constructors. For example, wrapper class for
int has two overloaded constructors. One constructor takes int as argument and
another takes string argument.
• Integer aNumber = new Integer(2);
• Integer anotherNumber = new Integer("2005");
• One constructor can call another overloaded constructor of the same class by using
this keyword.
• One constructor can call constructor of its super class by using the super keyword. ]

Example – Constructor Overloading

38 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

4.10.3. Method Overriding


When a method in a subclass has the same return type and signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within the subclass, always the method in the
subclass is invoked. The method inherited from the superclass will be hidden.

Example – Method Overriding

• When a class defines a method with same method name, argument types, argument
order and return type as a method in its super class, its called method overriding.
• The method in the super class is said to be overridden by the method in the subclass.
• Overriding method actually replaces the behavior in super class for a subclass.

Diploma – Object Oriented Programming 39


Accredited Course Provider

4.10.4. Rules for overriding

• Methods overriding cannot be declared more private than the super class method.
• Any exceptions declared in overriding method must be of the same type as those
thrown by the super class, or a subclass of that type.
• Methods declared as final cannot be overridden.
• An overriding method can be declared as final as the keyword final only suggests that
this method cannot be further overridden.
• Methods declared as private cannot be overridden as they are not visible outside the
class.
• Overriding method can call the overridden method (just like any other method) in its
super class with keyword super.
• The call super.method() will invoke the method of immediate super class.
• Though keyword super is used to refer super class, method call

Overloading methods. Overriding method.

• Overloaded methods supplement • An overriding method replaces the


each other. method it overrides.
• Overloading methods may have • An overriding method must have
different argument lists of different argument lists of identical type and
types. order.
• The return type may be different for • The return type must be same as that
overloaded methods of overridden method.
• Since overloading methods are • The overriding method must not throw
essentially different methods, there is checked exceptions which cannot be
no restriction on exceptions they thrown by the original method.
can throw.

4.11. 'Is a', 'has a' relationship

4.11.1. The Generalization (Inheritance) and 'is-a' relationship

Generalization is the result of abstracting the common attributes and behavior from a group
of closely related classes and moving them into a common super class. Specialization is the
inverse of generalization.
A common test for generalization is the IS-A test. Generalization may also look for following
phrases in problem definition to identify the inheritance.

• "is a"
• "is a type of"
• "is a kind of"

40 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

For example, if part of problem definition says 'Dog IS AN animal', implementation will more
likely have Animal class and Dog class will be the subclass of the Animal class.

4.11.2. The Composition and 'has-a' relationship

Composition is the relationship between a class and its constituent parts.


• Composition passes the “HAS-A” test.
Example: An Automobile 'has-a' Engine.
• Composition also passes the 'life and death' test. The parts have the same life as the
whole. Example: A Polygon has points, and the points live and die with the Polygon
object.

4.12. Variables are shadowed and methods are overridden

When a class member variable is accessed through an object reference, the variable to be
selected depends on the declared class of the object reference variable.

However, when a method is called on through an object reference, the actual method
invoked depends on the type of an object reference.

A subclass can have a variable with the same name as a variable in the parent class. This is
called as shadowing the parent class variable. It is not overriding of variable.

4.13. Late binding


in any method call, actual method to invoke is determined by the 'Class' (or type) of an object
on which the method is called and not on the type of variable holding the object reference. In
addition, this is decided at runtime.

Diploma – Object Oriented Programming 41


Accredited Course Provider

5. Collections
A collection (sometimes called a container) is simply an object that groups multiple elements
into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit
data from one method to another. Collections typically represent data items that form a
natural group, like a poker hand (a collection of cards), a mail folder (a collection of letters),
or a telephone directory (a collection of name-to-phone-number mappings).
If you've used Java -- or just about any other programming language -- you're already familiar
with collections. Collection implementations in earlier versions of Java included Vector,
Hashtable, and array. While earlier versions of Java contained collection implementations,
they did not contain a collections framework.

5.1. What Is a Collections Framework?


A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain three things:

• Interfaces: abstract data types representing collections. Interfaces allow collections to


be manipulated independently of the details of their representation. In object-oriented
languages like Java, these interfaces generally form a hierarchy.
• Implementations: concrete implementations of the collection interfaces. In essence,
these are reusable data structures.
• Algorithms: methods that perform useful computations, like searching and sorting, on
objects that implement collection interfaces. These algorithms are said to be
polymorphic because the same method can be used on many different implementations
of the appropriate collections interface. In essence, algorithms are reusable
functionality.

The best known examples of collections frameworks are the C++ Standard Template Library
(STL), and Smalltalk's collection classes.

5.2. What are the Benefits of a Collections Framework?

• It reduces programming effort: By providing useful data structures and algorithms, a


collections framework frees you to concentrate on the important parts of your program,
rather than the low-level plumbing required to make it work. By facilitating
interoperability among unrelated APIs (as described below), the collections framework
frees you from writing oodles of adapter objects or conversion code to connect APIs.
• It increases program speed and quality: The collections framework does this
primarily by providing high-performance, high-quality implementations of useful data
structures and algorithms. Also, because the various implementations of each interface
are interchangeable, programs can be easily tuned by switching collection
implementations. Finally, because you're freed from the drudgery of writing your own
data structures, you'll have more time to devote to improving the quality and
performance of the rest of the program.
• It allows interoperability among unrelated APIs: The collections interfaces will
become the "lingua franca" by which APIs pass collections back and forth. If my
network administration API furnishes a Collection of node names, and your GUI
toolkit expects a Collection of column headings, our APIs will interoperate seamlessly
even though they were written independently.
• It reduces the effort to learn and use new APIs: Many APIs naturally take collections
on input and output. In the past, each such API had a little "sub-API" devoted to
manipulating its collections. There was little consistency among these ad-hoc

42 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

collections sub-APIs, so you had to learn each one from scratch and it was easy to
make mistakes when using them. With the advent of standard collections interfaces,
the problem goes away.
• It reduces effort to design new APIs: This is the flip-side of the previous advantage:
designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections. They just use the standard collections interfaces.
• It fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.

5.3. Are there any Drawbacks?


Historically, collections frameworks have been quite complex, which gave them a reputation
for having a steep learning curve. We believe that Java's new collections framework breaks
with this tradition, as you will learn for yourself in the following lessons.

5.4. Interfaces
The core collection interfaces are the interfaces used to manipulate collections, and to pass
them from one method to another. The basic purpose of these interfaces is to allow
collections to be manipulated independently of the details of their representation. The core
collection interfaces are the heart and soul of the collections framework. When you
understand how to use these interfaces, you know most of what there is to know about the
framework. The core collections interfaces are shown below:

The core collection interfaces form a hierarchy: a Set is a special kind of Collection, and a
SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two
distinct trees: a Map is not a true Collection.
To keep the number of core collection interfaces manageable, the JDK doesn't provide
separate interfaces for each variant of each collection type. (Among the possible variants are
immutable, fixed-size, and append-only.) Instead, the modification operations in each
interface are designated optional: a given implementation may not support some of these
operations. If an unsupported operation is invoked, a collection throws an
UnsupportedOperationException. Implementations are responsible for documenting which
of the optional operations they support. All of the JDK's general purpose implementations
support all of the optional operations.

Diploma – Object Oriented Programming 43


Accredited Course Provider

The four sections that follow teach you how to use each of the four basic core collection
interfaces. In particular, they describe the idioms that allow you to use these interfaces
effectively.

5.5. Generics
When you take an element out of a Collection, you must cast it to the type of element that is
stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not
check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so
that it can be checked. Once the compiler knows the element type of the collection, the
compiler can check that you have used the collection consistently and can insert the correct
casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

// Removes 4-letter words from c. Elements must be strings


static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}

Here is the same example modified to use generics:

// Removes the 4-letter words from c


static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();

5.6. Collection
The Collection interface is the root of the collection hierarchy. A Collection represents a
group of objects, known as its elements. Some Collection implementations allow duplicate
elements and others do not. Some are ordered and others unordered. The JDK doesn't
provide any direct implementations of this interface: It provides implementations of more
specific subinterfaces like Set and List. This interface is the least common denominator that
all collections implement. Collection is used to pass collections around and manipulate them
when maximum generality is desired.

5.7. Set
A Set is a collection that cannot contain duplicate elements. As you might expect, this
interface models the mathematical set abstraction. It is used to represent sets like the cards
comprising a poker hand, the courses making up a student's schedule, or the processes
running on a machine.

5.8. List
A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the List each
element is inserted. The user can access elements by their integer index (position). If you've
used Vector, you're already familiar with the general flavor of List.

44 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

5.9. Map
A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key
can map to at most one value. If you've used Hashtable, you're already familiar with the
general flavor of Map.

The last two core collection interfaces ( SortedSet and SortedMap) are merely sorted
versions of Set and Map. In order to understand these interfaces, you have to know how
order is maintained among objects. Even if you don't plan to use SortedSet or SortedMap,
read the following section if you plan to sort Lists.

5.10. Object Ordering


There are two ways to order objects: The Comparable interface provides automatic natural
order on classes that implement it, while the Comparator interface gives the programmer
complete control over object ordering. Note that these are not core collection interfaces, but
underlying infrastructure.
Now that you know all about object ordering, here are the last two core collection interfaces:

5.10.1. SortedSet
A SortedSet is a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. The SortedSet interface is used
for things like word lists and membership rolls.

5.10.2. SortedMap
A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and
telephone directories.

5.11. General info


• A collection is a single object representing a group of objects known as its elements.
• Six collection interfaces: Collection, Set, List, SortedSet, Map, SortedMap.

5.11.1. Set
• A group of objects with no duplication
• SortedSet -- subinterface of Set
• TreeSet -- sorted
• HashSet-- best performance, unordered.
• LinkedHashSet-- since jdk 1.4

5.11.2. List
• A subinterface of Collection
• A group of objects with duplicate elements
• ArrayList -- like Vector, but its methods are not synchronized.
• LinkedList -- quick sequential access.

5.11.3. Vector
• Has been retrofitted to implement List interface.
• Provides methods for working with dynamic arrays of varied element types.
• Its methods are synchronized.

Diploma – Object Oriented Programming 45


Accredited Course Provider

• Slower access.

5.11.4. Vector vs. ArrayList


• one slower, the other faster
• one has synchronized methods by default, the other is not.
• prefer ArrayList

5.11.5. Map
• Maps keys and values.
• Hashtable -- historical implementation.
• SortedMap
• HashMap
• TreeMap
• LinkedHashMap
• IdentityHashMap
• WeakHashMap

46 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Example Vector
import java.lang.Integer;
import java.util.Enumeration;
import java.util.Vector;

class VectorEx
{
public static void main(String args[])
{
Vector v=new Vector(10,10);
for (int i=0;i<20;i++)
{
v.addElement(new Integer(i)); //adding an integer object
}
System.out.println("Vector in original order using an Enumeration");
for (Enumeration e=v.elements();e.hasMoreElements();)
{
System.out.print(e.nextElement()+" ");
}
System.out.println();

System.out.println("Vector in original order using elementAt");


for (int i=0;i<v.size();i++)
{
System.out.print(v.elementAt(i)+" ");
}

System.out.println();

// Print out the original vector


System.out.println("\nVector in reverse order using elementAt");
for (int i=v.size()-1;i>=0;i--)
{
System.out.print(v.elementAt(i)+" ");
}
System.out.println();

System.out.println("\nVector as a String");
System.out.println(v.toString());
}
}

Diploma – Object Oriented Programming 47


Accredited Course Provider

Example HashSet

import java.util.*;

class HashSetEx
{
public static void main(String args[])
{
HashSet h = new HashSet();
h.add("b");
h.add("z");
h.add("x");
h.add("g");
h.add("442");
h.add("222");
h.add("3232");
System.out.println("the hash set is");
System.out.println(h+"\n");
System.out.println("the size of hash set is "+h.size());
}
}

Example TreeSet

import java.util.*;

class TreeSetEx
{
public static void main(String args[])
{
TreeSet t=new TreeSet();
t.add("a");
t.add("d");
t.add("c");
t.add("b");
System.out.println(" the tree set is as follows");
System.out.println(t +"\n");
t.remove("c");
System.out.println("after removing the elements 3 is as follows :");
System.out.println(t +"\n");
t.add("5");
t.add("4");
t.add("7");
System.out.println("after adding more element s is as follows:");
System.out.println(t +"\n");
System.out.println("the part of the tree set upto the element is as
follows:");
System.out.println(t.headSet("b"));
System.out.println(" the part of the tree set from the element is as
follows:");
System.out.println(t.tailSet("b"));
}
}
48 Diploma – Object Oriented Programming
[Type text]
Accredited Course Provider

Example LinkList

import java.util.*;

class LisnkListEx
{
public static void main(String args[])
{
LinkedList l=new LinkedList();
l.add("NCC");
l.add("BIT");
l.add("BCS");
l.add("ACS");
System.out.println("the linked List after adding the first 3 elements is as
follows :\n"+l+"\n");
l.addFirst("before BIT");
l.addLast("before ACS ");
System.out.println("the linked List after adding two more elements is as
follows :\n"+l+"\n");
System.out.println("the location of element in the linked list :"+l.get(2)+"\n");
l.remove("ACS");
System.out.println("the linked list after removing the element 'ACS' is as
follows :\n"+l+"\n");
l.set(3,"SCJP");
System.out.println("the linked list after changing the fourth is as follows
:\n"+l+"\n");
}
}

Example - ArrayList

Diploma – Object Oriented Programming 49


Accredited Course Provider

6. Process Models

6.1. Iterative and Incremental Development

Define outline Assign requirements Design system


requirements to increments architecture

Develop system Valida te Integrate Valida te


increment increment increment system
Final
system
System incomplete

• The incremental approach to development, allows to reduce the rework in the


development process, and gives customers some opportunities to delay decisions on
their detailed requirements until they have some experience with the system.

• In an incremental development process customers identify in outline the services to


be provided by the system.

• They identify which of the services are the most important and which are least
important to them.

• A number of delivery increments are then defined with each increment providing a
subset of the system functionality.

• The allocation of services to increments are then defined with each increment
depends on the service priority.

• The highest priority services are delivered first to the customers.

• Once the system increments have been identified the requirements for the service to
be delivered in the first increment are defined in detail and developed the most
appropriate development process.

• During the development further requirement analysis, for later increment can take
place, but charges for the current increment cannot be accessed.

• Once an increment is completed and delivered, part of the system will be functional,
then the new increments are completed. They are integrated with existing increment
so the system functionality improves with each delivered increment.

50 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Advantages

Disadvantages

Diploma – Object Oriented Programming 51


Accredited Course Provider

6.2. Evolutionary Prototyping

6.2.1. What is Evolutionary Prototype

Concurr ent
activities

Initial
Specification
version

Outline Intermediate
Development
description versions

Final
Validation
version

• Evolutionary Prototyping is based on the idea of developing initial implementation,


exposing to user comments and refining this through many stages until an adequate
system has been developed.
• This approach to development was used initially for those systems which are difficult
or impossible to specify, but now it has become one of the main techniques of
development.

Advantages

Disadvantages

52 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

6.3. Unified Process


The Unified Process or UP is a popular iterative and incremental software development
process framework. The most well known and extensively documented refinement of the
Unified Process is the Rational Unified Process or RUP.
The Unified Process is not simply a process, but rather an extensible framework which can
and should be customized for specific organizations and/or projects. The Rational Unified
Process is, similarly, a customizable framework. As a result, it is often impossible to say
whether a refinement of the process was derived from UP or from RUP, and so the names
tend to be used interchangeably.
The name Unified Process (as opposed to Rational Unified Process) is generally used to
describe the generic process, including those elements which are common to most
refinements. The UP name is also used to avoid potential issues of copyright infringement
since Rational Unified Process and RUP are trademarks of IBM.

Characteristics

Iterative and Incremental


The Unified Process is an iterative and incremental development process. The Elaboration,
Construction and Transition phases are divided into a series of time boxed iterations. (The
Inception phase may also be divided into iterations for a large project.) Each iteration results
in an increment, which is a release of the system that contains added or improved
functionality compared with the previous release.
Although most iterations will include work in most of the process disciplines (e.g.
Requirements, Design, Implementation, Testing) the relative effort and emphasis will change
over the course of the project.

Use Case Driven


In the Unified Process, Use Cases are used to capture the functional requirements and to
define the contents of the iterations. Each iteration takes a set of Use Cases or scenarios
from requirements all the way through implementation, test and deployment.

Architecture Centric
The Unified Process insists that architecture sit at the heart of the project team's efforts to
shape the system. Since no single model is sufficient to cover all aspects of a system, the
Unified Process supports multiple architectural models and views.
One of the most important deliverables of the process is the executable architecture baseline
which is created during the Elaboration phase. This partial implementation of the system
serves to validate the architecture and act as a foundation for remaining development.
Risk Focused
The Unified Process requires the project team to focus on addressing the most critical risks
early in the project life cycle. The deliverables of each iteration, especially in the Elaboration
phase, must be selected in order to ensure that the greatest risks are addressed first.
Project Lifecycle
Profile of a typical project showing the relative sizes of the four phases. The Unified Process
divides the project into four phases:
1. Inception
2. Elaboration
3. Construction

Diploma – Object Oriented Programming 53


Accredited Course Provider

4. Transition

Inception Phase
Inception is the smallest phase in the project, and ideally it should be quite short. If the
Inception Phase is long then it is usually an indication of excessive up-front specification,
which is contrary to the spirit of the Unified Process.
The following are typical goals for the Inception phase.
1. Establish a justification or business case for the project
2. Establish the project scope and boundary conditions
3. Outline the Use Cases and key requirements that will drive the design tradeoffs
4. Outline one or more candidate architectures
5. Identify risks
6. Prepare a preliminary project schedule and cost estimate

The Lifecycle Objective Milestone marks the end of the Inception phase.
Elaboration Phase
During the Elaboration phase the project team is expected to capture a healthy majority of
the system requirements. However, the primary goals of Elaboration are to address known
risk factors and to establish and validate the system architecture.
The architecture is validated primarily through the implementation of an Executable
Architecture Baseline. This is a partial implementation of the system which includes the core,
most architecturally significant, components. It is built in a series of small, time boxed
iterations. By the end of the Elaboration phase the system architecture must have stabilized
and the executable architecture baseline must demonstrate that the architecture will support
the key system functionality and exhibit the right behavior in terms of performance, scalability
and cost.
The final Elaboration phase deliverable is a plan (including cost and schedule estimates) for
the Construction phase. At this point the plan should be accurate and credible since it should
based on the Elaboration phase experience and since significant risk factors should have
been addressed during the Elaboration phase.
The Lifecycle Architecture Milestone marks the end of the Elaboration phase.
Construction Phase
Construction is the largest phase in the project. In this phase the remainder of the system is
built on the foundation laid in Elaboration. System features are implemented in a series of
short, time boxed iterations. Each iteration results in an executable release of the software.
The Initial Operational Capability Milestone marks the end of the Construction phase.

54 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Transition Phase

The final project phase is Transition. In this phase the system is deployed to the target users.
Feedback received from an initial release (or initial releases) may result in further
refinements to be incorporated over the course of several Transition phase iterations. The
Transition phase also includes system conversions and user training.
The Product Release Milestone marks the end of the Transition phase.

Rational Unified Process


The Rational Unified Process (RUP) is a popular iterative software development process
created by the Rational Software Corporation, now a division of IBM. The RUP is an
extensive refinement of the (generic) Unified Process.

The RUP is not a single concrete prescriptive process, but rather an adaptable process
framework. It is intended to be tailored, in the sense that development organizations and
software project teams will select the elements of the process that are appropriate for their
needs.
The Rational Unified Process (RUP) is also a software process product, originally developed
by Rational Software, and now available from IBM. The product includes a hyperlinked
knowledge base with sample artifacts and detailed descriptions for many different types of
activities. RUP is included in the IBM Rational Method Composer (RMC) product which
allows customization of the process.

Principles and best practices


RUP is based on a set of software development principles and best practices, for instance:
• Develop software iteratively
• Manage requirements
• Use component based architecture
• Visually model software
• Verify software quality
• Control changes to software

Develop software iteratively


Given the time it takes to develop large sophisticated software systems it is not possible to
define the problem and build the solution in a single step. Requirements will often change
throughout a project's development, due to architectural constraints, customer's needs or a
greater understanding of the original problem. Iteration allows the project to be successively
refined and addresses a project's highest risk items as the highest priority task. Ideally each
iteration ends up with an executable release, this helps reduce a project's risk profile, allows
greater customer feedback and helps developers stay focused.
The RUP uses iterative and incremental development for the following reasons:
• Integration is done step by step during the development process, limiting it to fewer
elements.
• Integration is less complex, making it more cost effective.
• Parts are separately designed and/or implemented and can be easily identified for
later reuse.
• Requirement changes are noted and can be accommodated.

Diploma – Object Oriented Programming 55


Accredited Course Provider

• Risks are attacked early in development since each iteration gives the opportunity for
more risks to be identified.
• Software architecture is improved by repeated scrutiny.
Using iterations, a project will have one overall phase plan, but multiple iteration plans.
Involvement from stakeholders is often encouraged at each milestone. In this manner,
milestones serve as a means to obtain stakeholder buy in while providing a constant
measure against requirements and organizational readiness for the pending launch.

Manage requirements
Requirements Management in RUP is concerned with meeting the needs of end users by
identifying and specifying what they need and identifying when those needs change. Its
benefits include the following:
• The correct requirements generate the correct product; the customer's needs are
met.
• Necessary features will be included, reducing post-development cost.
RUP suggests that the management of requirements has the following activities:
• Analyze the problem - is about agreeing on the problem and creating the measures
that will prove its value to the organization.
• Understand stakeholder needs - is about sharing the problem and value with key
stakeholders and finding out what their needs are surrounding the solution idea.
• Define the system - is about creating features from needs and outlining use cases,
activities which show nicely the high-level requirements and the overall usage model
of the system.
• Manage the scope of the system - is about modifying the scope of what you will
deliver based on results so far and selecting the order in which to attack the use-case
flows.
• Refine the system definition - is about detailing use-case flows with the
stakeholders in order to create a detailed Software Requirements Specification (SRS)
that can serve as the contract between your team and your client and that can drive
design and test activities.
• Manage changing requirements - is about how to handle incoming requirement
changes once the project has begun.
Use component-based architecture
Component-based architecture creates a system that is easily extensible, intuitively
understandable and promotes software reuse. A component often relates to a set of objects
in object-oriented programming.
Software architecture is increasing in importance as systems are becoming larger and more
complex. RUP focuses on producing the basic architecture in early iterations. This
architecture then becomes a prototype in the initial development cycle. The architecture
evolves with each iteration to become the final system architecture. RUP also asserts design
rules and constraints to capture architectural rules. By developing iteratively it is possible to
gradually identify components which can then be developed, bought or reused. These
components are often assembled within existing infrastructures such as CORBA and COM,
or Java EE.

Visually model software


Abstracting your programming from its code and representing it using graphical building
blocks is an effective way to get an overall picture of a solution. Using this representation,
technical resources can determine how best to implement a given set of inter-related logics.
It also builds an intermediary between the business process and actual code through

56 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

information technology. A model in this context is visualization and at the same time a
simplification of a complex designs. RUP specifies which models are necessary and why.
The Unified Modeling Language (UML) can be used for modeling Use-Cases, Class
diagrams and other objects. RUP also discusses other ways to build models.

Verify software quality


[

Quality assessment is the most common failing point of all software projects, since it is often
an afterthought and sometimes even handled by a different team. RUP assists in planning
quality control and assessment by building it into the entire process and involving all
members of a team. No worker is specifically assigned to quality; RUP assumed that each
member of the team is responsible for quality during the entire process. The process focuses
on meeting the expected level of quality and provides test workflows to measure this level.

Control changes to software


In all software projects, change is inevitable. RUP defines methods to control, track and
monitor changes. RUP also defines secure workspaces, guaranteeing a software engineer's
system will not be affected by changes in another system. This concept ties in heavily with
component based architectures.

The Rational Unified Process is structured along two dimensions:


1. Time – division of the life cycle into phases and iterations
2. Process components – production of a specific set artifacts with well-defined
activities
Structuring a project along the time dimension involves the adoption of the following time-
based phases:
• Inception – specifying the project vision
• Elaboration – planning the necessary activities and required resources; specifying
the features and designing architecture
• Construction – building the product as a series of incremental iterations
• Transitions – supplying the product to the user community (manufacturing,
delivering, and training)
Structuring the project along the process component dimension includes the following
activities:
• Business Modeling - the identification of desired system capabilities and user needs
• Requirements – a narration of the system vision along with a set of functional and
nonfunctional requirements
• Analysis and design – a description of how the system will be realized in the
implementation phase
• Implementation – the production of the code that will result in an executable system
• Test – the verification of the entire system
• Deployment – the delivery of the system and user training to the customer
Benefits of RUP

• The Rational Unified Process is an iterative process. Built into the iterative
approach is the flexibility to accommodate new requirements or tactical
changes in business objectives.

Diploma – Object Oriented Programming 57


Accredited Course Provider

• Models used in RUP, especially those specified using the UML, provide
semantically rich representations of the software systems under development. This
allows the system to easily understood and expressed.
• The rationale behind the rational unified process’s focus on models rather than
paper documents is to minimize the overhead associated with generating and
maintaining documents and to minimize the relevant information content.
• Development under Rational Unified Process is architecture centric. The process
focus on the early development and baseline of a software architecture (component
based).
• Development under Rational Unified Process is use case driven. The Rational
Unified Process places strong emphasis on building systems based on a thorough
understanding of how the delivered system will be used.
• The notions of use cases and scenarios are used to align the process flow from
requirement capture through testing and to provide traceable threads through
development to the delivered system.
• The Rational Unified Process supports object oriented techniques. Each model
is object oriented. Rational Unified Process models are based on the concepts of
objects and classes and the relationships among them and they use the UML as its
notation
• The Rational Unified Process is a configurable process. Although no single
process suitable for all software development organizations, The Rational Unified
Process is tailor able and can be scaled to fit the needs of projects ranging from
small software development teams to large development organizations.
• The Rational Unified Process encourages ongoing quality control and risk
management. Quality assessment is built into the process, in all activities and
involving all participants, using objective measurements and criteria. Risk
management is also built into the process, so that risks to the success of the project
are identified and attacked early in the process, when there is time to react.

58 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

7. Testing - Object oriented system testing


In an object oriented system, four levels of testing can be identified:

1. Testing the individual operations associated with objects – These are functions or
procedures and the black-box and white-box approaches may be used.

2. Testing individual object classes – The principle of black-box testing is unchanged but the
notion of an equivalence class must be extended to cover related operation sequences.

3. Testing clusters of objects - Strict top-down or bottom-up integration may be inappropriate


to create groups of related objects. Other approaches such as scenario based testing should
be used.

4. Testing the object oriented system - V & V against the systems requirements specification
is carried out in exactly the same way as for any other type of system.

7.1. Object Class Testing


When testing objects, complete test coverage should include:
1. The testing in isolation of all operations associated with the object;
2. The setting and interrogation of all attributes associated with the object;
3. The exercise of the object in all possible states. This means that all events that cause a
state change in the object should be simulated.

7.2. Object Integration


In object oriented systems, there is no obvious ‘top’ that provides for the integration nor is
there a clear hierarchy of objects that can be created. Clusters therefore have to be created
using knowledge of there operation and the features of the system that are implemented by
these clusters. There are three possible approaches to integration testing that may be used:

1. Use-case or scenario- based testing – Testing can be based on the scenario descriptions
and object clusters created to support the use-cases that relate to that mode of use.

2. Thread testing – Thread testing is based on testing the system’s response to a particular
input or set of input events.

3. Object interaction testing – An intermediate level of integration testing can be based on


identifying ‘method – message ‘paths. These are traces through a sequence of object
interactions which stop when an object operation does not call on the services of any other
object.

Diploma – Object Oriented Programming 59


Accredited Course Provider

8. Design Patterns
In software engineering a design pattern is defined as a “description of a solution to a
recurring problem within a context, proven by experience to lead to a superior result
when properly applied”. A design pattern isn't a finished design that can be transformed
directly into code; it is a description or template for how to solve a problem that can be used
in many different situations. Object-oriented design patterns typically show relationships and
interactions between classes or objects, without specifying the final application classes or
objects that are involved. Algorithms are not thought of as design patterns, since they solve
computational problems rather than design problems.
Patterns are a way to document good, proven, general solutions to common recurring
problems. These solutions may be applied within a specified context and serve to resolve
various forces, potential hazards that may cause problems later. Application of a pattern may
have consequences good or bad as described by the pattern.

8.1. Uses
Design patterns can speed up the development process by providing tested, proven
development paradigms. Effective software design requires considering issues that may not
become visible until later in the implementation. Reusing design patterns helps to prevent
subtle issues that can cause major problems and improves code readability for coders and
architects familiar with the patterns.
Often, people only understand how to apply certain software design techniques to certain
problems. These techniques are difficult to apply to a broader range of problems. Design
patterns provide general solutions, documented in a format that doesn't require specifics tied
to a particular problem.

8.2. Documentation
The documentation for a design pattern should contain enough information about the
problem that the pattern addresses, the context in which it is used, and the suggested
solution. Nonetheless, authors use their own layouts to document design patterns, and these
layouts usually resemble the essential parts. The authors usually include additional sections
to provide more information, and organize the essential parts in different sections, possibly
with different names.
The following is a layout which is used to document design patterns:
1. Pattern Name and Classification: Every pattern should have a descriptive and
unique name that helps in identifying and referring to it. Additionally, the pattern
should be classified according to a classification. This classification helps in
identifying the use of the pattern.
2. Problem or Intent: This section should describe the goal behind the pattern and the
reason for using it. It resembles the problem part of the pattern.
3. Motivation: This section provides a scenario consisting of a problem and a context in
which this pattern can be used. By relating the problem and the context, this section
shows when this pattern is used.
4. Applicability: This section includes situations in which this pattern is usable. It
represents the context part of the pattern.
5. Structure: A graphical representation of the pattern. Class diagrams and Interaction
diagrams can be used for this purpose.
6. Forces or Consequences: Explains the issues surrounding the problem, how the
solution resolves those issues and the potential benefits and trade-offs of applying
the solution.
7. Known Uses: Provides some descriptions of a few known situations that have
successfully applied this solution

60 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

8. Also Known As: A pattern could have more than one name. These names are
documented in this section
9. Related Patterns: This section includes other patterns that have some relation with
this pattern, so that they can be used along with this pattern, or instead of this
pattern. It also includes the differences this pattern has with similar patterns

Note: Not all published patterns will contain all of these sections and some may have
additional sections. However, all well-written software design patterns will have at least the
first six sections and, preferably, all nine.

8.3. Classification
Design patterns can be classified in terms of the underlying problem they solve. The
researchers collected 23 of the most commonly used general purpose design patterns that
are application domain independent and classified them in three categories.
Examples of problem-based pattern classifications are as follows:

8.4. Creational patterns


This design patterns is all about class instantiation. Deals with the best way to create
instances. Creates objects at run time and not at compile time.
1. The factory pattern - it deals with the problem of creating objects (products)
without specifying the exact class of object that will be created
2. The abstract factory pattern - provides a way to encapsulate a group of individual
factories that have a common theme
3. The builder pattern - is used to enable the creation of a variety of complex objects
from one source object.
4. The prototype pattern – used when the type of objects to create is determined by
a prototypical instance, which is cloned to produce new objects.
5. The singleton pattern - is used to restrict instantiation of a class to one (or a few)
objects.

8.5. Structural patterns


Structural patterns describe how classes and objects can be combined to form larger
structures

Structural patterns include:


1. Adapter - makes things work after they are designed
2. Bridge makes things work before they are
3. Composite is a composition of objects –
4. Decorator provides an enhanced interface
5. Facade represents an entire subsystem
6. Flyweight is a pattern for sharing objects
7. Proxy represents another object

8.6. Behavioral Patterns


Behavioral patterns are concerned with the assignment of responsibilities between
objects, or, encapsulating behavior in an object and delegating requests to it.

Behavioral patterns include:


1. Observer defines the way a number of classes can be notified of a change.
2. Mediator uses a class to simplify communication between other classes
3. Memento provides a way to capture an object’s state

Diploma – Object Oriented Programming 61


Accredited Course Provider

4. Chain of responsibility allows a number of classes to attempt to handle a


request
5. Template provides an abstract definition of an algorithm
6. Interpreter provides a definition of how to include language elements in a
program
7. Strategy encapsulates an algorithm inside a class
8. Visitor adds functions to a class
9. State provides a memory for a class‘s instance variables
10. Command encapsulates an action as an object
11. Iterator formalizes the way we move through a list of data

8.7. Documentation of Patterns

1.Singleton
Pattern name & Classification – Singleton creational pattern
Problem or Intent - This is a creational design pattern which ensures that a class has only a
single occurrence (instance) and there is global point of access to it
Motivation
There are some situations where a class should have exactly one instance:
• There can be only one president for a country
• There can be only one printer spooler for a system though it can have many
printers
• There can be only one window manager for a system
Applicability
The singleton pattern is used when:
• There must be exactly one instance of a class
• It must be accessible to clients from a well known access point
• Sole instance should be extendable by sub classing, but clients should be able to use
extended class without modifying their code
Structure

Singleton

static uniqueInstance
singletonData

static Instance()
SingletonOperation()
GetsingletonData()

Consequences
Benefits
• Controlled access to single instance
• Reduced name space by avoiding global variables

62 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

• Permits refinement of operations through sub classing


• Can be used to permits variable number of instances rather than just one

Diploma – Object Oriented Programming 63


Accredited Course Provider

2.Abstract Factory

Pattern name & Classification – Abstract Factory creational pattern

Problem or Intent - This is a creational design pattern which provides an interface for
creating families of related objects without specifying their concrete classes.

Motivation
Consider a composite class which must contain the same members but be created differently
depending on the application. For example, you could have a document which would be
printed differently depending on the printer being used, but would still have to contain the
same information. The idea behind abstract factory is that you can pass a class (the factory)
to the constructor which has a standard interface. This interface is then used by the
constructor, but the methods it uses are implemented differently for each kind of factory
Applicability
The Abstract factory is used when:
• A system should be independent of how its products are created, composed and
represented.
• A system should be configured with one of multiple families of products.
• A family of related product objects is designed to be used together and you need to
enforce this constraint.
• You want to provide a class library of products and you want to reveal just their
interfaces not their implementations

Structure

64 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Consequences
Benefits
• It isolates concrete classes
• It makes exchanging product families easy
• It promotes consistency among products
Drawback
• Supporting new kinds of product is difficult

3.Decorator
Pattern name & Classification – Decorator structural pattern
Problem or Intent – This is a structural pattern which attaches additional responsibilities to
an object dynamically. Decorators provide a flexible alternative to sub classing for extending
functionality.
Motivation
Sometimes it is necessary to add responsibilities to individual objects not to an entire class.
A graphical user interface toolkit, for example should let you add properties like borders or
behaviors like scrolling to any user interface component.
One way to add responsibilities is with inheritance. Inheriting a border from another class
puts a border around every sub class instance. This is inflexible, however, because the
choice of border is made statically. A client can’t control how and when to decorate the
component with a border.

A more flexible approach is to enclose the component in another object that adds the border.
The enclosing object is called a decorator. The decorator conforms to the interface of the
component it decorates so that its presence is transparent to the component’s clients. The
decorator forwards requests to the component and may perform additional actions (such as
drawing a border) before or after forwarding. Transparency lets you nest decorators
recursively, thereby allowing an unlimited number of added responsibilities.
For example suppose we have a TextView object that displays text in a window. TextView
has no scroll bars by default, because we might not always need them. When we do we can
use a ScrollDecorator to add them. Suppose we want to add a thick black border around the
TextView we can use a BorderDecorator to add this as well. We simply compose the
decorators with the TextView to produce the desired result.
The ScrollDecorator and BorderDecorator classes are subclasses of Decorator which is an
abstract class for visual components that decorate other visual components.

Diploma – Object Oriented Programming 65


Accredited Course Provider

Applicability
Decorator Pattern can be applied:
• To add responsibilities to individual objects dynamically and transparently, that is
without affecting other objects.
• For responsibilities that can be withdrawn.
• When an extension by subclassing is impractical.
Structure

Consequences
Benefits
• More flexibility than static inheritance
• Avoids feature laden classes high up in the hierarchy
Drawback
• Lots of Little objects

4.Composite
Pattern name & Classification – Composite structural pattern
Problem or Intent – Compose objects into tree structures in order to represent part-whole
hierarchies. Composite lets clients treat individual objects and compositions of objects
uniformly.
Motivation – Used in situations where users need to build complex diagrams out of simple
components. For example- Building hierarchical file structures or Building graphical objects.

66 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Applicability

The Composite pattern is used when:


• You need to represent part-whole hierarchies of objects
• You want clients to be able to ignore the difference between compositions of objects.
(Clients will treat all objects in the composite structure uniformly).

Structure

A typical composite object structure might look like given below:

Consequences

Benefits

• Defines class hierarchies consisting of primitive objects and composite objects


• Makes the client simple that is clients can treat composite structures and individual
objects uniformly
• Makes it easier to add new kinds of components

Drawback
• Cannot restrict the components of composite by applying constraints

5.Observer
Pattern name & Classification – Observer behavioural pattern

Diploma – Object Oriented Programming 67


Accredited Course Provider

Problem or Intent – Defines a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated automatically.

Motivation

A common side-effect of partitioning a system into a collection of cooperating classes is the


need to maintain consistency between related objects. You don’t want to achieve
consistency by making the classes tightly coupled, because that reduces the reusability.
There observer patterns are used to solve this problem.
The key objects in this pattern are subject and observer. A subject may have any number of
dependent observers. All observers are notified whenever the subject undergoes a change in
state. In response, each observer will query the subject to synchronize its state with the
subject’s state.
This kind of interaction is also known as publish-subscribe. The subject is the publisher of
notifications. It sends out these notifications without having to know who its observers are.
Any number of observers can subscribe to receive the notifications.

Applicability
The Observer pattern can be used in any of the following situations:
• When an abstraction has two aspects, one dependent on the other. Encapsulating
these aspects in separate objects lets you vary and reuse them independently.
• When a change to one object requires changing others, and you don’t know how
many objects need to be changed.
• When an object should be able to notify other objects without making assumptions
about who these objects are. In other words, you don’t want these objects tightly
couples.

Structure

68 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Consequences
Benefits
• Abstract coupling between subject and observer
• Support for broadcast communication
Drawback
• Unexpected Updates
6. Iterator
Pattern name & Classification – Iterator behavioural pattern
Problem or Intent – The intent of this design pattern is to provide a way to access the
elements of an aggregate object sequentially without exposing its underlying representation.
In other words, an Iterator allows a client to access a content of a certain data structure
without knowing about the internal representation of the contents.
Motivation - A data structure such as list should give the user a way to access its elements
in such a way that it does not expose its internal structure. Also, you should be able to
manipulate that list in different ways, depending on what you want to accomplish, but at the
same time you do not want to all your manipulation procedures into the list interface even if
you can predict which ones you might need. The Iterator Pattern allows you to do those
things. The idea of this pattern is to take the responsibility for access and manipulation of the
data structure out of the list object and put it into the Iterator object. The Iterator class will
define the interface for accessing the data structure's elements. This way we can define
different Iterators for different ways of manipulating a data structure.
Applicability
The Iterator pattern can be used in any of the following situations:
• To access an aggregate object’s contents without exposing its internal
representation.
• To support multiple traversals of aggregate objects.
• To provide a uniform interface for traversing different aggregate structures (that is to
support polymorphic iteration).
Structure

Consequences
Benefits
• Iterator Pattern supports variations in the traversal of an aggregate - Every time you
want to change the traversal algorithm, you just replace the Iterator instance with a
different one.

Diploma – Object Oriented Programming 69


Accredited Course Provider

• Iterators simplify the Aggregate interface.


• More than one traversal can be pending on an aggregate - An Iterator keeps track of
its own traversal state. Therefore you can have more than one traversal in progress at
once.

70 Diploma – Object Oriented Programming


[Type text]
Accredited Course Provider

Advantages of Design Patterns

Disadvantages of Design Patterns

Diploma – Object Oriented Programming 71

You might also like