Академический Документы
Профессиональный Документы
Культура Документы
Course Description
Course SE30 Course name Object Oriented Concepts
number
Author Nagendra R Setty, nagendra_setty@infosys.com, E&R Dept, Mysore
Sivasubramanyam Y, Sivasubramanyam_Y@infosys.com, E&R Dept, Chennai
Pre-requisites for attending course: Must have completed:
Computer Hardware and System Software Concepts, Programming Fundamentals
Suggested course duration 01 day
Modification Log
References
1. G. Booch. Obj ect -orient ed analysis and design wit h applicat ions. Benj amin/ Cummings,
Redwood Cit y, CA, 1994.
2. Brad J. Cox, Andrew J. Novobilski Obj ect -Orient ed Programming – An evolut ionary
approach, Addison-Wesley, 1991.
3. J. Rumbaugh, M. Blaha, W. Premerlani, F. Eddy, W. Lorensen. Obj ect -orient ed
modeling and design. Prent ice-Hall, Englewood Cliffs, N.J., 1991.
4. ht t p:/ / j ava.sun.com
5. UML Tut orial at ht t p:/ / www.smart draw.com/ t ut orials/ soft ware-uml/ uml.ht m
Table of Contents
PURPOSE................................................................................................................... 1
1. INTRODUCTION .................................................................................................... 1
2. PROGRAMMING TECHNIQUES.................................................................................... 2
2.1. UNSTRUCTURED PROGRAMMING .................................................................................. 2
2.1.1. Limit at ions of Unst ruct ured Programming ....................................................... 2
2.2. PROCEDURAL PROGRAMMING ..................................................................................... 3
2.2.1. Limit at ions of Procedural Programming .......................................................... 6
2.3. OBJECT ORIENTED PROGRAMMING................................................................................ 6
2.4. SUMMARY......................................................................................................... 7
3. INTRODUCTION TO OBJECT ORIENTED CONCEPTS......................................................... 8
3.1. OBJECT .......................................................................................................... 8
3.2. CHARACTERISTICS OF OBJECTS ................................................................................. 11
3.2.1. Abst ract ion ........................................................................................... 11
3.2.2. Encapsul at ion ........................................................................................ 14
3.2.3. Message passing...................................................................................... 14
3.3. CLASS .......................................................................................................... 16
3.3.1. Access specif iers in a cl ass......................................................................... 17
3.3.2. Exampl e of a cl ass................................................................................... 17
3.4. DIFFERENCE BETWEEN CLASS AND OBJECT ...................................................................... 21
3.5. DIFFERENCE BETWEEN MESSAGE PASSING AND PROCEDURE CALLS............................................... 21
3.6. UML CLASS DIAGRAMS.......................................................................................... 22
3.6.1. Represent ing a cl ass in Cl ass diagrams.......................................................... 22
3.7. SUMMARY....................................................................................................... 24
4. ADVANCED CONCEPTS IN OBJECT ORIENTED TECHNOLOGY ............................................ 25
4.1. RELATIONSHIPS................................................................................................. 25
4.1.1. Is-A rel at ionship ..................................................................................... 26
4.1.2. Part -Of and Has-A rel at ionships .................................................................. 28
4.1.3. Uses-A Rel at ionship ................................................................................. 28
4.1.4. Represent ing Mul t ipl icit y of Rel at ionships in Cl ass Diagrams .............................. 28
4.2. INHERITANCE ................................................................................................... 28
4.2.1. The ‘ prot ect ed’ access specif ier .................................................................. 28
4.2.2. Mul t il evel Inherit ance .............................................................................. 28
4.2.3. Mul t ipl e Inherit ance ................................................................................ 28
4.2.4. General izat ion and Special izat ion................................................................ 28
4.3. ABSTRACT CLASSES............................................................................................. 28
4.4. POLYMORPHISM................................................................................................. 28
4.4.1. Met hod/ Funct ion Overl oading .................................................................... 28
4.4.2. Met hod/ Funct ion Overriding ...................................................................... 28
4.5. SUMMARY....................................................................................................... 28
5. OBJECT ORIENTED DESIGN METHODOLOGY ................................................................ 28
5.1. COMPARISON OF PROCEDURAL AND OBJECT ORIENTED PROGRAMMING.......................................... 28
5.2. APPROACH TO OBJECT ORIENTED DESIGN ...................................................................... 28
5.3. BEST PRACTICES IN OO DESIGN METHODOLOGY ................................................................ 28
6. RECENT TRENDS IN OO TECHNOLOGY ....................................................................... 28
6.1. THE CONCEPT OF INTERFACE ................................................................................... 28
6.2. THE CONCEPT OF A COMMON BASE CLASS....................................................................... 28
PURPOSE
Over a period of t ime comput er soft ware and syst ems have undergone several improvement s
and have evolved int o complex syst ems. It is easy t o underst and and design such complex
syst ems if t hey are modeled exact ly based on t he real world. Today, most complex soft ware
syst ems are designed and built using Obj ect Orient ed Programming Languages.
This course int roduces t he principles and concept s behind t he paradigm of “ Obj ect Orient ed
Programming” . The concept s learnt in t his course will help t he readers t o underst and t he
design of Obj ect Orient ed syst ems and also is a st epping st one t o learn Obj ect Orient ed
Programming languages.
1. Introduction
Since t he 1980s, soft ware development process has changed significant ly. It s evolut ion has
been mot ivat ed largely by t he need t o speed up soft ware product ion, address business and
indust ry needs and t o deliver more value t o t he end users.
Despit e gains, t he indust ry st ill faces long development cycles. There are st ill some gaps
bet ween what is required and what is available. These limit at ions have moved t he soft ware
indust ry t o embrace Obj ect Orient ed t echnology because of it s pot ent ial t o significant ly
increase developer product ivit y1 and encourage innovat ion.
int o a self-sufficient ‘ obj ect ’ t hat can be used wit hin a program or in ot her programs. Wit h
Obj ect Orient ed programs, programmers can use obj ect s, cont aining dat a and t he associat ed
processing inst ruct ions, like basic building blocks t o assemble a bigger program.
The ot her advant age of Obj ect Orient ed Programming is t hat t he obj ect s are modeled on real
world ent it ies2. This enables modeling complex syst ems of real world int o manageable
soft ware solut ions. This course helps a soft ware engineer t o underst and t he fundament als
behind t he Obj ect Orient ed Programming paradigm.
1
Developer Productivity: A measure of t he amount of qualit y code t hat can be writ t en by a developer
in a given amount of t ime.
2
Entity: Somet hing t hat exist s as a part icular and separat e unit .
2. Programming techniques
This chapt er is a short survey of t he various programming t echniques t hat exist . They can be
classified as:
• Unst ruct ured Programming (Assembly language3 programming)
• Procedural Programming (Assembly language, C programming)
• Obj ect Orient ed Programming (C++, Java, Smallt alk, C#)
*OREDO'DWD
3URJUDP
3
Assembly Language: Similar t o machine language, but provides names for numeric inst ruct ions
present in t he machine language, making it easy for t he programmer. Machine language is t he language
which a Cent ral Processing Unit (CPU) of a comput er underst ands and consist s only of numbers.
4
Global Variables: The variables t hat are declared out side any funct ion body. These variables exist for
t he ent ire life-cycle of t he program. Global variables can be accessed from anywhere wit hin t he
program.
5
Local Variables: The variables t hat are declared wit hin a funct ion body. Their scope is limit ed t o
wit hin t he funct ion. Local variables cannot be accessed out side t he funct ion.
Procedural Programming is useful t o bring order in t he maze of algorit hms available t o solve a
part icular problem. Procedural Programming is support ed by all modern programming
languages.
Common funct ionalit ies are grouped int o separat e modules or procedures. The code wit hin a
funct ion can be writ t en and maint ained independent ly of ot her funct ions as long as t he
signat ure of t he funct ion does not change.
#include <stdio.h>
#define MAX_ITEMS 5
/* Global Variables */
/* Store Item codes, cost and Discount information in Arrays */
int iItemCodes [] = { 101, 102, 103, 104, 105 };
float fItemCost [] = { 899.95f, 250.0f, 102.0f, 798.95f, 254.6f };
float fItemDiscount [] = { 0.0f, 0.0f, 0.0f, 10.5f, 30.0f};
/***********************************************************
* Function: main()
* Description: Entry point. Accepts user input and acts.
* Input Parameters:
* int argc - Number of command line arguments
* char **argv The command line arguments passed
* Returns: 0 on success to the operating system
***********************************************************/
6
Modularity: The propert y of a syst em t hat has been decomposed int o a set of cohesive but loosely
coupled modules.
/* Initialize index to -1 */
iIndex = -1;
/* Get the array index of the selected item */
for (iCount = 0; iCount < MAX_ITEMS; iCount++) {
if (iItemCodes [iCount] == iItemCode) {
/* Item code found in list. break */
iIndex = iCount;
break;
}
}
if (iIndex == -1) {
/* Could not find the item code entered by user */
printf ("Please select a valid Item code\n");
}
else {
printf ("Price: %.2f\n", fItemCost [iIndex]);
printf ("Discount: %.2f %%\n", fItemDiscount [iIndex]);
}
return 0;
}
/***********************************************************
* Function: fnGetItemName
* Description: Given an Item ID, returns the name.
* Input Parameters:
* int iItemId - Id of the Item
* Returns: Name of the item.
***********************************************************/
case 101:
pcItemName = "Acme Shoes";
break;
case 102:
pcItemName = "Best T-Shirt";
break;
case 103:
pcItemName = "Superb sox";
break;
case 104:
pcItemName = "Swanky Jacket";
break;
case 105:
pcItemName = "Leather Belt";
break;
default:
pcItemName = "ERROR: Unknown Item";
break;
};
return pcItemName;
}
/***********************************************************
* Function: fnDisplayItems
* Description: Displays all the items with code in
* a tabular form.
* Input Parameters: NONE
* Returns: void
***********************************************************/
void fnDisplayItems() {
/***********************************************************
* End of kiosk.c
***********************************************************/
Here, any change t o t he body of t he procedure (funct ion) does not affect t he procedure call
in t he funct ion ‘ main’ as long as t he signat ure of t he funct ion remains same.
The procedure calls act as an int erface bet ween t he main funct ion (calling funct ion) and t he
called funct ions.
Spaghet t i code refers t o t he code where t he flow becomes very convolut ed7 especially when
t here are mult iple developers working on t he same code. This happens due t o frequent
modificat ion of code wit hout analyzing t he impact of code change.
7
Convoluted: Having numerous overlapping coils or folds; Complicat ed
2.4. Summary
This chapt er covered t he following point s:
• Programming t echniques can be classified as:
o Unst ruct ured Programming
o Procedural Programming
o Obj ect Orient ed Programming
• Procedural programming: Programming Technique where common funct ionalit ies are
grouped int o separat e modules or procedures
• Limit at ions of Procedural programming
o As code grows maint enance becomes difficult
o Maj or changes t o funct ionalit y requires changes across modules and in a lot of
places
o Large code base of procedural code t ends t o t urn int o spaghet t i code as more
and more changes are made
• Object Oriented Programming: Programming Technique where dat a st ruct ures are
combined wit h relat ed funct ions t o creat e reusable obj ect s
There are several concept s in Obj ect Orient ed Programming. These are discussed in t he
following sect ions.
3.1. Object
An ‘ obj ect ’ means “anything that can be seen or touched; material thing”
An Obj ect in t he soft ware world means a bundle of relat ed variables and funct ions (also
known met hods). Soft ware obj ect s are oft en used t o model real world obj ect s from everyday
life.
Obj ect s are t he key t o underst and t he Obj ect Orient ed t echnology. One can look around and
see many real world examples of an obj ect .
The real world obj ect s and soft ware obj ect s share t wo charact erist ics: They have St at e and
Behavior.
State: St at e is a well defined condit ion of an it em. A st at e capt ures t he relevant aspect s of
t he syst em’ s hist ory efficient ly.
Examples:
A ‘ Bicycle’ obj ect :
• St at e: Current speed
• Behavior: Slow down, Accelerat e
A ‘ Dog’ obj ect :
• St at e: Name, Color, Breed, Hungry or not
• Behavior: Bark, Wag Tail, Fet ch, Eat
A ‘ Car’ obj ect :
• St at e: Number of gears, Number of doors, Current Speed, Current Gear, Seat ing
capacit y
• Behavior: Slow down, Accelerat e, Change gears
For example, let us consider t he ‘ Car’ obj ect . The Color, Model and
Manuf act ured year of t he car does not change. These can be
considered as passive st at e. Speed, Current gear are st at e which
change due t o t he behavior of car
For example, a car obj ect has a behavior ‘accelerat e’ which act s on
t he st at e of t he obj ect like ‘current speed’
Real world obj ect s can be represent ed in soft ware using obj ect s!
Example 1: A dog can be represent ed in sof t ware program as an obj ect in an animat ion or
gaming program.
Example 2: A car or an aut omobile can be represent ed using obj ect s in sof t ware used by an
aut omobile ret ailer or car manuf act urer.
Example 3: Bank account inf ormat ion can be represent ed in sof t ware used in banks using an
Account Obj ect . Similarl y act ivit ies of a bank t eller 8 can be represent ed using a Teller
obj ect .
Everyt hing a soft ware obj ect knows (St at e) and can do (Behavior) is represent ed by variables
and met hods (funct ions) in t he obj ect respect ively.
Figure 3-2 shows t hat t he variables form t he cent er (nucleus) of an obj ect . Met hods surround
t he variables (dat a) and hide t he variables from ot her obj ect s in t he program.
The behavior of t he obj ect (funct ions/ met hods) forms t he int erface t o t he ext ernal world.
Usually, t he st at e (variables) of an obj ect is not direct ly exposed t o ot her obj ect s or t he
ext ernal world. However in some cases a programmer may expose some variables t o t he
ext ernal world.
Modularity: The source code of an obj ect can be writ t en and maint ained independent ly of
ot her obj ect s. An obj ect can easily be passed around across modules in a program.
8
Teller: An employee of a bank who receives and pays out money (Also known as cashier in some
countries).
Information Hiding: An obj ect has a public int erface for ot her obj ect s t o communicat e wit h
it . The obj ect can maint ain privat e dat a (informat ion) and met hods, which can be changed at
any t ime wit hout affect ing ot her obj ect s t hat int eract wit h it .
Example: One does not have t o underst and t he int ernal working of an engine and gearbox
mechanism in a car t o drive t he car..
3.2.1. Abstraction
Abst ract ion helps simplif y t he underst anding and using of any complex syst em. The purpose of
abst ract ion is t o hide informat ion t hat is not relevant and t o simplify it by comparing it t o
somet hing similar in t he real world.
Figure 3-3: One doesn’t have to understand how the engine works in order to drive
Let us t ake a few examples t o underst and t he concept of abst ract ion.
Example 1: A car engine is a complex machine wit h lot of moving part s int ernally, but t he
f inal use of an engine is not f or how it s int ernal component s work, but what it can give out
ext ernally. In t he simplest t erms, a running engine can cause t he rot at ion of a wheel (It s
behavior as a whole, not t he int ernal part s.) The speed of t he engine can be cont rolled by
t he amount of f uel supplied t o t he engine (behavior as a whole again).
In t he next level of abst ract ion, we can visualize t hat an engine is one of t he complex part s
t hat make up a car. The ot her part s t hat make up a car can be t he gear box, chassis et c. To
drive a car, however one doesn’ t have t o underst and t he int ernal working of t he car engine.
All t he end user needs t o know t o be able t o use t he car is how t o use t he car’ s st eering
wheel, brake pedal and accelerat or pedal (Gas pedal) gears et c.
Abst ract ion means “ The process of forming of general and relevant concept from more
complex scenarios” .
Let us t ake anot her example of how abst ract ion helps in simplifying one of t he most complex
problems int o many simpler but manageable problems.
Example 2: The CPU (Cent ral Processing Unit ) of a comput er is a complex device wit h
millions of el ect ronic component s made on t he silicon chip9. No human being can possibly
understand the int eract ions bet ween all t hese million component s when they look at t he
chip. So how exact ly is such a complex syst em built ?
To st art wit h, t here are basic elect ronic component s like resist ors, capacit ors and t ransist ors
et c. which f orm t he building blocks of any elect ronic syst em.
9
Silicon Chip: A wafer t his slice of silicon on which microscopic elect ronic circuit s are built .
These basic el ect ronic component s are used t o creat e Boolean Logic10 gat es11 which hide t he
complexit y by creat ing circuit s12 using t he basic elect ronic component s. Boolean logic gat es
f orm t he basic building blocks of Digit al Elect ronics13. To use or underst and a Boolean Logic
gat e, one doesn’ t have t o really know t he det ails of how t he elect ronic circuit works
int ernally.
More complex digit al circuit s14 are built using t he Boolean gat es. A digit al circuit can use
hundreds of Boolean gat es! A digit al circuit can be a ‘Count er’ , which count s binary numbers
or a ‘Regist er’ which st ores binary numbers. A complex digit al circuit is represent ed and
used f or it s behavior and not because of how it works int ernal ly (st at e)!
A much more complex device like t he CPU is built using several digit al circuit s. The number
of such complex digit al circuit s used in a CPU is f ar less compared t o say, creat ing a CPU
using millions of raw el ect ronic component s wit hout any abst ract ion! This example is a
classic case where abst ract ion has helped reduce t he huge complexit y of t he problem t o
small manageable unit s.
Similar t o t he examples above, a large complex problem in soft ware can be simplified t o an
easy and manageable scale by using abst ract ion. Abst ract ion is one of t he goals t hat Obj ect
Orient ed t echnology achieves. A soft ware obj ect is not hing but an abst ract ion of a real world
obj ect t hat it represent s and hides t he complexit y wit hin.
Note 1: Abst ract ion is a general concept used t o build complex syst ems.
Abst ract ion is used not j ust in soft ware, but in all real life scenarios.
Abst ract ion is t he key t o simplify a complex design int o smaller, manageable
part s which t hen become t he component s of a bigger and complex syst em. The
human mind cannot t rack more t han a few paramet ers simult aneously.
Abst ract ion helps in hiding t he complexit y wit hin a smaller component of a
syst em.
Note 2: Abst ract ion is not a feat ure of Obj ect orient ed concept s alone. Even in
procedural language programming, abst ract ion can be achieved t o a limit ed
ext ent by hiding complex int ernals t hrough well formed business logic and
funct ions.
10
Boolean Logic: A logic syst em developed by Brit ish mat hemat ician, Prof. George Boole. This logic
applies t o variables which have only t wo values (0 or 1 – Binary values).
11
Gate: A computer circuit with several inputs but only one output that can be activated by particular
combinations of inputs.
12
Circuit (Or Electronic Circuit): A group of electronic components connected to perform a specific
function.
13
Digital Electronics: The branch of electronics dealing with information in binary form (Zeroes and
Ones).
14
Digital Circuit: A circuit which operates in the manner of a switch, either "on" or "off" (0s and 1s). All
computers are built on digital circuits.
3.2.2. Encapsulation
Encapsulat ion means t he localizat ion of t he informat ion or knowledge wit hin an obj ect .
Encapsulation is also called as “Information Hiding”. Encapsulat ion means “ In a capsule” .
Obj ect s encapsulat e dat a and implement at ion det ails. To t he out side world, an obj ect is a
black box15 t hat exhibit s a cert ain behavior. The behavior of t his obj ect is what which is
useful for t he ext ernal world or ot her obj ect s. An obj ect exposes it s behavior by means of
met hods or funct ions.
The set of funct ions an obj ect exposes t o ot her obj ect s or ext ernal world act s as t he int erface
of t he obj ect .
Example: Consider t he ‘car’ obj ect . The dashboard of t he car (t he speedomet er, f uel gauge
and ot her met ers), st eering wheel and t he f oot pedals (Brakes, Accel erat or) t oget her f orm
t he int erf ace of t he car obj ect . (Ref er t o Figure 3-5) Ot her obj ect s int eract wit h t he car
obj ect using t his int erf ace provided by car obj ect .
Figure 3-5: The dashboard of a car acts as an interface to the external world
One obj ect int eract s wit h anot her obj ect by invoking met hods (or funct ions) on t hat obj ect .
Through t he int eract ion of obj ect s, programmers achieve a higher order of funct ionalit y
which has complex behavior.
15
Black Box: When t he exact inner workings of a given syst em aren’ t known out side, it is known as
Black Box. Such syst ems are only charact erized by t he behavior t hey exhibit ext ernally.
Figure 3-6: Person interacts with car using the steering wheel, gauges on dashboard and pedals
Example 1: A car by it self is not capable of any act ivit y. The car is usef ul when t he person
who drives int eract s wit h it using t he st eering wheel, brake and accelerat or pedals. So, here
a ‘person’ obj ect is int eract ing wit h t he ‘car’ obj ect by using t he st eering wheel and pedals
(message passing). The speedomet er and f uel gauge on t he dashboard provide inf ormat ion t o
t he person obj ect . In ot her words t he person is passing messages using t he int erf ace provided
by t he car obj ect and vice versa.
One obj ect invoking met hods on anot her obj ect is known as Message passing. It is also
referred t o as Method Invocation. (Refer t o Figure 3-7.)
2EMHFW 2EMHFW
0HWKRGV 0HWKRGV
,QYRNHV
'DWD 'DWD
V
NH
YR
,Q
,QYRNHV
,QYRNHV
,QYRNHV
,Q
YR
2EMHFW 2EMHFW
NH
V
0HWKRGV 0HWKRGV
,QYRNHV
'DWD 'DWD
Somet imes t he obj ect get t ing invoked requires addit ional informat ion f or a cert ain
operat ions.
For example, consider a bank account obj ect . To do a deposit operat ion, t he amount t o be
deposit ed has t o be supplied while invoking t he deposit met hod.
3.3. Class
A class is a represent at ion of an abst ract dat a t ype16 in a specific programming language. A
class can be used like any ot her primit ive dat a t ypes17 which are part of t he programming
language.
Programming languages do provide simple dat a t ypes. But most real lif e dat a18 is complex in
nat ure.
Examples: A cust omer’ s address cannot be st ored in a simple dat a t ype of any programming
language. A ‘Dat e’ cannot be direct ly represent ed in any simple dat a t ype, because it needs
at least t hree f ields f or ‘Day of Mont h’ , ‘Mont h’ and ‘Year’ .
A class enables programmers t o creat e complex dat a st ruct ures modeled aft er real life dat a.
A class is a mechanism t o bind dat a and it s relat ed funct ions t oget her. When defining a class,
we are essent ially defining a new dat a t ype, which can be used similar t o any ot her built -in
dat a t ype19 provided by t he programming language.
The const it uent s20 of a class are called members. There are t wo t ypes:
16
Abstract Data Type: A set of dat a values and associat ed operat ions t hat are precisely specified
independent of any part icular implement at ion.
17
Primitive Data Type: Simple dat a t ypes like int egers, charact er, f loat ing point numbers et c.
numbers support ed by most programming languages.
18
Real Life Data: Dat a t hat is used as part of day t o day life. Examples: Dat e, Address of a person,
Bank account det ails, Salary det ails of a person and Order det ails in a business t ransact ion et c.
19
Built-in Data Type: These are dat a t ypes t hat are already available in a programming language.
Usually ref ers t o t he primit ive dat a t ypes. However, some high level languages may have some complex
dat a t ypes also built in t o t he language.
20
Constituent: Component ; t hat which forms t he part of somet hing
public: Accessible t o all. Ot her obj ect s can also access t his member variable or funct ion.
private: Not accessible by ot her obj ect s. Privat e members can be accessed only by t he
met hods in t he same class.
protected: Under usual circumst ances it is t he same t o privat e. However, it has a small
difference. This difference will be explained lat er. (Sect ion 4.2.1 The ‘prot ect ed’ access
specif ier)
Example: The public int erf ace of a car consist s of Gas pedal, Brake pedal, St eering Wheel,
Speed and Fuel Gauges on t he dashboard, which are accessibl e t o ot her obj ect s (such as
driver).
In a car, t he engine part s like gearbox and pist on21 can be viewed as ‘privat e’ . They are not
accessible t o ot her obj ect s.
#define SUNDAY 00
#define MONDAY 01
#define TUESDAY 02
#define WEDNESDAY 03
#define THURSDAY 04
#define FRIDAY 05
#define SATURDAY 06
21
Gearbox, Piston: Int ernal component s of an aut omobile engine.
class Date {
private:
short m_day;
short m_month;
short m_year;
public:
Date(short day, short month,
short year);
// Useful functions
short getDayOfWeek ();
Date getNextDay ();
Date getPrevDay ();
...
};
/************************************************************
* End of date.h
************************************************************/
The implement at ion of t he class refers t o implement at ion of t he met hods declared in t he
class. Wit h reference t o t he above ‘ Dat e’ example, t he implement at ion of t he class refers t o
writ ing t he body for t he funct ions declared.
Note 2: In modern languages like Java and C#, a class is declared and
implement ed in t he same file.
#include “date.h”
/************************************************************
* Date - Constructor
* Creates the Date object. Initializes the member variables
* m_day, m_month, m_year with the values passed.
*
* PARAMETERS:
* short day – Day of Month
* short month – Month
* short month - Year
************************************************************/
/************************************************************
* getDayOfMonth
* Returns the Day of the Month.
*
* PARAMETERS: None
* RETURNS: The day of month
************************************************************/
Short Date::getDayOfMonth () {
return m_day;
}
...
...
/************************************************************
* End of date.cpp
************************************************************/
A class is a blueprint of an obj ect . In ot her words, a class is a prot ot ype of an obj ect of a
part icular kind.
An int eger is a dat a t ype. To use an int eger dat a t ype, we have t o declare a variable of t ype
int . i.e. we have t o creat e an inst ance of t ype int eger. Similarly t o use a class, we have t o
creat e an inst ance of it .
Instance of a class: (Obj ect ) An inst ance is a part icular realizat ion of a class, represent ing a
real t hing in t he real world. Each inst ance of a class has it s own values for t he dat a. Met hods
declared in a class can be invoked only on an inst ance of t he class.
A class is a definit ion of a set of dat a and met hods. When memory space for t his dat a is
act ually allocat ed, we say t hat t he class is inst ant iat ed.
In a program we can have many variables of t he t ype int eger declared. Similarly mult iple
obj ect s (inst ances) of t he same class can be creat ed.
The example below shows t wo inst ances of ‘Dat e’ class being used in a program. One inst ance
is used t o st ore t he st art dat e of a course, and t he ot her is used t o st ore t he end dat e of t he
course.
#include “date.h”
/***********************************************************
* Function: main()
* Description: Entry point. Accepts user input and acts.
* Input Parameters:
* int argc - Number of command line arguments
* char **argv The command line arguments passed
* Returns: 0 on success to the operating system
***********************************************************/
/************************************************************
* End of coursedates.cpp
************************************************************/
In t he above code example, endDat e.get DayOfMont h() invocat ion operat es only on t he dat a of
t he obj ect ‘endDat e’ . Similarly, st art Dat e.get DayOfMont h () invocat ion operat es only on t he
dat a of t he obj ect ‘st art Dat e’ .
An obj ect on t he ot her hand, is an inst ance of a class. There can be many inst ances of t he
same class. Each inst ance of a class (obj ect ) will have it s own dat a.
Figure 3-8: Difference between Calls in procedural language and Message passing
Message passing on t he ot her hand refers t o one obj ect invoking met hods on anot her obj ect .
The met hod invoked on an obj ect usually operat es on t he dat a of t hat part icular obj ect .
There are several t ypes of diagrams in UML specificat ion. This course focuses on t he Class
diagrams, which is one of t he import ant part s of UML.
A Class diagram gives a logical view of a syst em t hat shows t he exist ence of classes, t heir
cont ent s and t heir relat ionships. In ot her words, a Class diagram is used t o pict orially
represent classes, t heir cont ent s and t heir relat ionships.
The class has met hods t o get and set t he values of t he above member variables. The Figure
3-9 shows a represent at ion of class in UML format .
A class is represent ed by a rect angle which has t hree port ions in it . Each of t he port ions is for
a specific represent at ion:
1. The name of t he class
The not at ion ‘+’ indicat es t hat t he Met hod or Variable is public and t he not at ion ‘-’ indicat es
t hat t he Met hod or Variable is privat e.
Note: ‘#’ is used t o indicat e prot ect ed member variables and met hods
in a class.
There are many more not at ions in Class diagrams. More not at ions will be int roduced along
wit h t he relevant concept s furt her in t his course.
The above UML Class diagram represent ing t he Loan class is also shown in t he code below.
class Loan {
private:
double LoanAmount;
float InterestRate;
int Duration;
int CustomerID;
public:
float GetInterestRate();
double GetLoanAmount();
int GetDuration();
int GetCustomerID();
void SetDuration(int Duration);
void SetLoanAmount(double LoanAmount);
void SetInterestRate(float InterestRate);
void SetCustomerID(int CustomerID);
};
3.7. Summary
This chapt er covered t he following point s:
4.1. Relationships
Ident ifying t he relat ionships bet ween different classes and t heir inst ances would help in
designing bet t er Obj ect Orient ed solut ions. The different kinds of relat ionships are discussed
in t he following sect ions.
For discussing relat ionships, let us consider a Banking relat ed case st udy.
Case Study: Global Commerce Bank provides different t ypes of loans. For t his, t he bank
int ends t o develop a syst em. The IT Depart ment of t he bank has opt ed for Obj ect Orient ed
approach for t his syst em.
22
Floating Interest Rate: For some t ypes of loans, banks offer int erest rat e which keeps changing wit h
t ime based on t he economic sit uat ion.
23
Moratorium Period: Lead t ime aft er which t he repayment of loan st art s in case of large loans.
All loans are associat ed wit h a Cust omer. Also, t he bank’ s IT depart ment expect s t he syst em
t o be flexible t o int roduce a complet ely new loan scheme at a lat er point of t ime wit hout
making significant changes t o t he syst em.
All t hese loans have t o be paid back by cust omers t hrough Equat ed Mont hly Inst allment s24
(EMI). There are t hree t ypes of bank employees who deal wit h loans.
• Loan Advisors: Advises cust omers on various loans and can also init iat e loans. The
final approval of loans can be done only by t he Bank Manager.
• Bank Manager: Primarily responsible for approving all loans and fixing of special
int erest rat es for Business Loans. The bank manager can also init iat e loans
• Teller: Can accept EMIs.
The Class diagram for t he Housing Loan class is shown in Figure 4-1.
24
Equated Monthly Installments (EMI): It is a mont hly inst allment paid by t he person t o clear a loan.
EMI consist s of Part of t he principal amount and t he int erest incurred on t he loan.
class HousingLoan {
private:
int CustomerID;
int Duration;
float InterestRate;
double LoanAmount;
char TypeOfInterest;
public:
float GetInterestRate();
void SetInterestRate(float InterestRate);
double GetLoanAmount();
void SetLoanAmount (double LoanAmount);
int GetCustomerID();
void SetCustomerID (int CustomerID);
int GetDuration();
void SetDuration(int LoanDuration);
char GetTypeOfInterest();
void setTypeofInterest(char TypeofInterest);
};
Comparing t he definit ions of t he Loan class and HousingLoan class one can observe t hat :
• Bot h t he classes have Cust omerID, Durat ion, LoanAmount and Int erest Rat e as common
at t ribut es
• Bot h t he classes provide t he same set of met hods t o set t he values of t hese at t ribut es
and also t o get t he values of t hese at t ribut es
• The HousingLoan class has an addit ional at t ribut e called TypeOfInt erest and access
met hods t o get and set t he values for t his at t ribut e
Observe t hat t he HousingLoan class can be described using t he Loan class and t he addit ional
at t ribut e (TypeOfInt erest ) and t he met hods t o access TypeOfInt erest . The HousingLoan class
is relat ed t o t he Loan class and t his relat ionship is called “ Is-A” relat ionship.
The HousingLoan “ Is-A” Loan. This relat ionship is represent ed in Figure 4-2. The HousingLoan
is a specialized class when compared t o t he Loan class.
The Address at t ribut e of t he Propert yDet ails class can be defined as anot her class by it self.
The Address class has t he following at t ribut es:
• AddressLine1
• AddressLine2
• Cit y
• Zip
• St at e
The Propert yDet ails class is part of HousingLoan class. Such a relat ionship is called “ Part-Of”
relat ionship. Also, t he Address class is “ Part-Of” t he Propert yDet ails class. (refer t o Figure
4-3).
The HousingLoan “ Has-A” Propert yDet ails. Propert yDet ails “ Has-A” Address.
The “ Has-A” relat ionship is t he opposit e of “ Part -Of” relat ionship. The “ Has-A” relat ionship is
also known as Aggregation. The Class diagram depict ing t he “ Part -Of” and “ Has-A”
relat ionship is shown in Figure 4-4.
Example: Ref er t o Figure 4-5. The LoanAdvisor class uses a Loan class t o init iat e a Loan.
The Init iat eLoan met hod of LoanAdvisor “ Uses-A” Loan obj ect . Therefore, t he class
LoanAdvisor ‘Uses-A’ Loan obj ect . The line ( ) connect ing t he t wo classes
represent s t he associat ion.
Notation Meaning
1 One only
* Many (More t han one always)
0..1 Zero or One
0..* Zero or Many
1..* One or Many
Table 4-1: Notations to represent multiplicity
Examples: Table 4-2 shows examples of represent ing mult iplicit y of relat ionships.
Multiplicity Representation
One t o One Aggregat ion
A car can have only one
engine
Note: Mult iplicit y applies only t o Aggregat ion (Has-A) and Associat ion (Uses-
A) relat ionships. It does not apply t o Is-A (Inherit ance) relat ionship.
4.2. Inheritance
Some of us inherit propert y from our ancest ors. Every human being inherit s some of t he
genet ic qualit ies from eit her of t heir parent s. Why would one want t o inherit t heir parent s’
wealt h? One of t he obvious reasons could be t o build t he wealt h furt her from what has been
built by t he parent s.
Example: Consider t he case st udy of t he loan syst em in Global Commerce Bank. The bank
provides dif f erent kinds of loans. Some of t he at t ribut es t hat are common t o all loans are:
• LoanAmount
• Int erest Rat e
• Durat ion
• Cust omerID
In order t o build an OO solut ion f or t he loan syst em one could f irst st art by def ining a Loan
class which has t he above ment ioned at t ribut es along wit h relat ed met hods (ref er t o Figure
3-9 f or t he Class diagram represent at ion of t he Loan class).
Apart f rom t hese common at t ribut es of t he Loan class, t he Housing loan needs one more
at t ribut e called t he Int erest Type. Inst ead of redef ining t he HousingLoan class f rom t he
scrat ch one could inherit t he HousingLoan class f rom t he Loan class and add only t he
addit ional at t ribut e Int erest Type in it (ref er t o Figure 4-6).
Not e t hat t he in t he Figure 4-6 is used t o denot e “ Inherit s from” relat ionship.
This is a st andard convent ion in class diagrams. The class closer t o t he t riangle (| >) is t he
base class.
The HousingLoan class has “ Is-A” relat ionship wit h t he Loan class. The Loan class is t he base
class and t he HousingLoan class is t he derived class.
OO t echnology models around t he behavior of t he real world. In t he real world, one could
pass on t he inherit ed wealt h or genet ic qualit ies t hrough different generat ions.
The next obvious quest ion would be t o see if somet hing similar is possible in OO t echnology.
Can an inherit ed class become a parent class for anot her class? The answers t o such relat ed
quest ions are provided in t he next few sect ions.
Note 1: Inherit ance is not hing but “ Is-A” or “ Kind Of” relat ionship
Note 2: The biggest advant age of Inherit ance is t hat , code in base class need
not be rewrit t en in t he derived class. The member variables and met hods of
t he base class can be used in t he derived class as well.
Member variables or met hods t hat are declared as protected, are accessible t o t he classes
t hey are declared in and any class t hat inherit s t hem.
Consider t he case st udy of Global Commerce Bank. The BusinessLoan class inherit s from t he
Loan class. BusinessLoan represent s loans given t o small and medium businesses. The business
loan can be availed for a short t erm or a long t erm. The t ype of int erest can be eit her fixed
or float ing.
The business loan for large scale proj ect s offered by t he bank is almost similar, but also has a
morat orium period. Now inst ead of defining t he LargeBusinessLoan class, it can be derived
from BusinessLoan class wit h an addit ional at t ribut e ‘Morat oriumPeriod’ (refer t o Figure 4-7).
In t his example:
Conversely,
• HousingLoan class is a derived from Loan class
• BusinessLoan class is derived from Loan class
• LargeBusinessLoan class is derived from Business Loan class
Example: Let us t ake an example of a Hybrid Car t o underst and t he concept of Mult iple
Inherit ance (Ref er t o Figure 4-8).
A Fuel Car is one which runs on f uels like Gasol ine (Pet rol), Diesel et c. An Elect ric Car is one
which runs wit h elect ricit y as it s source of power. A Hybrid car is one which runs on t wo or
more sources of power. Some of t he hybrid cars run on bot h Gasoline (Pet rol) and Elect ricit y.
Note 2: Most of t he new OO languages like Small Talk, Java, C# do not support
Mult iple inherit ance. Mult iple Inherit ance is support ed in C++.
This process of ident ifying t he similarit ies among different classes is called Generalization.
The class which is ident ified aft er generalizat ion is t he base class. The classes over which t he
generalizat ion is made are t he derived classes.
The classes over which t he generalizat ion is built are viewed as Specialization.
Generalizat ion ident ifies t he common at t ribut es and behavior among different ent it ies
whereas specializat ion ident ifies t he dist inct at t ribut es and t heir behavior which different iat e
a derived class from t he ot her classes.
Example: The Loan class in t he Loan Syst em of t he Global Commerce Bank is an example of
Generalizat ion. The common at t ribut es and behavior among all t ypes of loan are:
Attributes Behavior
LoanAmount Get LoanAmount (); Set LoanAmount ();
Int erest Rat e Get Int erest Rat e(); Set Int erest Rat e();
Durat ion Get Durat ion(); Set Durat ion();
Cust omerID Get Cust omerID(); Set Cust omerID();
The classes corresponding t o t he various t ypes of loans are examples of specializat ion. i.e.,
HousingLoan, BusinessLoan, LargeBusinessLoan and ConsumerLoan. The Loan class is an
example of Generalizat ion.
A Generalizat ion–Specializat ion hierarchy is used t o depict t he relat ionship bet ween t he
generalized class and t he corresponding specialized classes. The Class diagram represent ing
t he Generalizat ion–Specializat ion hierarchy for t he loan syst em of t he Global Commerce Bank
is shown in Figure 4-9.
Ident ifying Generalizat ion and Specializat ion for given problem st at ement helps in removing
redundancy in code.
Abst ract classes provide an out line for behavior by means of met hod signat ures wit hout an
implement at ion. Such met hods are called as Abstract Methods.
There can be some scenarios where it is difficult t o implement all t he met hods in t he base
class. In such scenarios one can define t he base class as an abst ract class which signifies t hat
t his base class is a special kind of class which is not complet e on it s own.
A class derived from t he abst ract base class must implement t hose member funct ions which
are not implement ed in t he abst ract class.
Since t he abst ract class has incomplet e informat ion it would not be possible t o creat e an
inst ance of an abst ract class. In ot her words one cannot creat e an obj ect of an abst ract class
(cannot be inst ant iat ed).
Example: Let us consider t he case of sof t ware (Ref er t o Figure 4-10) which is used f or
Graphics. The base class ‘Shape’ has a f unct ion ‘Draw’ . The Shape class’ is abst ract and does
not implement t he met hod Draw. (Draw is an abst ract met hod).
6KDSH $EVWUDFWFODVV
'RHVQRWLPSOHPHQW
'UDZ 'UDZIXQFWLRQ
The Line, Rect angle, Circle and Oct agon classes are derived f rom Shape. The derived classes
implement t he abst ract met hod Draw. The Line class has t he code t o draw a st raight line in
t he f unct ion Draw. The Rect angle class has t he code t o draw a rect angle and so on.
Here, t he Shape class def ined t he out line f or all t he ot her derived classes using t he abst ract
met hod Draw.
To use an abst ract class one has t o first derive anot her class from t his abst ract class using
inherit ance and t hen provide t he implement at ion for t he abst ract met hods.
Note: If a derived class does not implement all t he abst ract met hods
(unimplement ed met hods), t hen t he derived class is also abst ract in nat ure and
cannot be inst ant iat ed.
4.4. Polymorphism
‘Poly’ means ‘many’ and ‘Morph’ means ‘form’ . Polymorphism refers t o an obj ect ’ s (not
class) abilit y t o behave different ly, depending on it s t ype. This feat ure provides a means t o
ext end an obj ect ’ s funct ionalit y.
Polymorphism brings t wo import ant feat ures t o t he obj ect s which are discussed in t he
following sect ions.
Example: Consider t he code snippet of t he class “ St ring” . The St ring class is a ut ilit y class
writ t en t o reduce complexit y of using st rings in code. Not e t hat C and C++ use charact er
arrays or point ers t o deal wit h st rings. The St ring class is designed t o encapsulat e t he
complexit y of managing a st ring.
class String {
private:
char* m_str;
public:
String (char* str);
String (int size);
...
...
void Append (int value);
void Append (float value);
void Append (char value);
void Append (String* str);
void Append (char* str);
}
The St ring class has a lot of f unct ions f or most commonly used operat ions on st rings. Let us
consider t he example of t he f ive ‘Append’ met hods in t he St ring class. All t he f ive met hods
are call ed ‘Append’ . All t he met hods have t he same name, but dif f erent signat ures.
The met hod “ Append (int value);” appends an int eger t o t he exist ing st ring. If t he st ring
cont ains “ INR ” and t he f unct ion Append(1) is invoked on t hat st ring obj ect , t hen it will
append t he int eger “ 1” t o t he st ring. The result ant st ring will cont ain “ INR 1” .
Similarl y, Append f unct ions are provided t o append a f loat ing point number or anot her
St ring it self . The code snippet below shows t he usage of overloaded f unct ions and helps t o
underst and t his concept f urt her.
// ********************************************************
// Final contents of StrRate is “INR 199.95 per 100 Items”
// ********************************************************
The concept of t he same funct ion name wit h different t ypes of paramet ers being passed is
called Funct ion Overloading.
Note 1: Two overloaded funct ions of same signat ure cannot have same
paramet ers but different ret urn t ypes. The example below is invalid because
it leads t o ambiguit y for t he compiler in choosing t he funct ion.
Note 3: Operat or overloading refers t o t he operat ors like ‘+’ being used for
different purposes based on t he dat a t ype on eit her side of t he operat or.
In case of t he int eger example below, t he ‘+’ does arit hmet ic addit ion.
St ring st r1 = “ Hello ” ;
St ring st r2 = “ World” ;
Example 1: Let us consider t he case of sof t ware used f or Graphics (Ref er t o Figure 4-11).
The base class ‘Shape’ has a f unct ion ‘Draw’ . The Shape class is abst ract and does not
implement t he met hod Draw.
6KDSH $EVWUDFW&ODVV
'RHVQRWLPSOHPHQW
'UDZ 'UDZIXQFWLRQ
The Line, Rect angle, Circle and Oct agon classes are derived f rom t he Shape class. The
derived classes implement t he f unct ion Draw. The Line class has t he code t o draw a st raight
line in t he f unct ion Draw. The Rect angle class has t he code t o draw a rect angle and so on.
Since all t he classes in t his example inherit f rom Shape class, we can generalize t hem as
shapes.
...
...
So, when t he met hod Draw is invoked as shown in t he above code snippet , on any class
generalized as a Shape class, t he respect ive Draw f unct ion of t he derived class is invoked.
This behavior of t he same funct ion having a different implement at ion is known as Met hod
Overriding. When a funct ion is overridden, t he funct ion name and signat ure will remain t he
same as declared in t he base class.
Example 2: (Ref er t o Figure 4-12) The base class ‘Loan’ provides a met hod called “ Report ”
which produces a report on t he loan det ails in a specif ic f ormat . The derived class
‘HousingLoan’ has overridden t his met hod ‘Report ’ t o generat e an ent irely dif f erent report
on Housing loan inf ormat ion it st ores.
/RDQ
B *+)!,/.;)1C%23)143(
B 8"! D%' ( )!
B 561 !87 )3E%7
B 9:1+ )3.F 5G%7
"! # $&%' ( )!
*+)!-,/.0)1 # $&%23)143(
561 !87 )# $&%7
9:1+- )3.; 5<# $=%7
>=561 !+87 )# $
>=*+)!,6.0)1 # $
>= "! # $
>= 9:1+ )3.; 5<# $ L&M NPO+Q R
?@A) # $ ST+UV
W RO TX Y
+RXVLQJ/RDQ
B HIA+D%+JK!
3 HIA# $&%+JK!3
3>= HIA# $ Z=T[-\ M V-]
@A) # $ ST+UV
W RO TX Y
4.5. Summary
This chapt er covered t he following point s:
• Relationships
o Is-A (Same as Kind-Of, Inherit ance)
o Part -Of
o Has-A (Same as Aggregat ion)
o Uses-A (Same as Associat ion)
• Inheritance: One class inherit s t he st at e and behavior from t he base class.
• Base Class: Same as Super class, Parent class
• Derived Class: Same as Sub class, child class
• Multilevel Inheritance: Inherit ance can span mult iple levels.
• Multiple Inheritance: One class inherit s from t wo or more base classes. Mult iple
inherit ance leads t o unwant ed complexit ies and is not used very oft en.
• Generalization: Process of ident ifying commonalit ies among different classes
• Specialization: Ident ifies dist inct at t ribut es and behavior which different iat e t he
derived classes from it s base class
• Abstract class: A class which out lines behavior, but not necessarily implement s all t he
behavior
o Abstract methods: Met hods in abst ract class, which t he abst ract class does not
implement
o An abst ract class cannot be inst ant iat ed. It has t o be derived int o sub classes.
The derived class can be inst ant iat ed only if it implement s all t he abst ract
met hods
• Polymorphism means “ Many forms” . Polymorphism helps great ly in ext ending t he
funct ionalit y of a class
o Method Overloading: Refers t o using t he same name t o denot e several
different operat ions. Met hod name remains same, signat ures differ
o Method Overriding: Refers t o t he pract ice of providing a different
implement at ion of a met hod in t he derived class. Met hod name and signat ure
remains same
Step 1. Ident ify all t he classes (Nouns; Type of obj ect s) in t he requirement
specificat ion
Step 2. Ident ify t he commonalit ies bet ween all or small groups of classes ident ified
(generalizat ion) if it is obvious. Do not force fit generalizat ion where it doesn’ t make
sense.
Step 3. In any given sit uat ion, st art wit h t he simplest obj ect which can be abst ract ed
int o individual classes
Step 4. Ident ify all t he member variables and met hods t he class should have
Step 5. Ensure t hat t he class is fully independent of ot her classes and cont ains all t he
at t ribut es25 and met hods necessary.
Step 6. Keep all t he dat a members privat e or prot ect ed
Step 7. The met hods in t he class should complet ely abst ract t he funct ionalit y
Step 8. The met hods in t he class should not be a f orce f it 26 of procedural code int o a
class
Step 9. Inherit and ext end classes from t he base classes ONLY IF t he sit uat ion has
scope for it
Step 10. Define t he relat ionships among t he classes (“ Has-A” , “ Uses-A” )
Step 11. Keep t he number of classes in your applicat ion under check (do not creat e any
unnecessary classes)
Example: Let us consider t he case st udy of Global Commerce Bank. The previous sect ions
have already shown t he Class diagrams f or various t ypes of loans of f ered by t he bank.
Now, let us consider t he port ion of t he syst em which deals wit h t he users of t he bank.
Specification:
(Ext ract from earlier case st udy of Global Commerce Bank. Refer t o t he case st udy in 4.1
Relat ionships)
Bank Manager: Primarily responsible for approving all loans and fixing of special int erest
rat es for Business Loans. The bank manager can also init iat e loans.
Let us apply t he above ment ioned st eps t o come out wit h a design.
Step 1: Identify all the classes (Nouns; Type of objects) in the requirement specification
25
Attribute: A charact erist ic associat ed wit h a person or t hing; in Obj ect Orient ed t echnology, it refers
t o t he member variables of a class.
26
Force Fit: Somet hing t hat does not fit in smoot hly or nat urally; forced t o fit
The common fact or of all t he t hree classes ident ified above is t hat t hey are all “ Employees”
of t he bank.
Step 3: In any given situation, start with the simplest object which can be abstracted into
individual classes
Step 4: Identify all the member variables and methods the class should have
• Class Employee
o Member Variables
EmployeeID
Email
o Met hods
Get / Set EmployeeID
Get / Set Email
Now, let us ident ify t he member variables and Met hods for t he rest of t he classes.
• Class LoanAdvisor
o Member Variables
EmployeeID
Email
o Met hods
Get / Set EmployeeID
Get / Set Email
Init iat eLoan
• Class BankManager
o Member Variables
EmployeeID
Email
o Met hods
Get / Set EmployeeID
Get / Set Email
Init iat eLoan
ApproveLoan
• Class Teller
o Member Variables
EmployeeID
Email
o Met hods
Get / Set EmployeeID
Get / Set Email
Accept EMI
Step 5: Ensure that the class is fully independent of other classes and contains all the
attributes and methods necessary
We can observe from our design t hat t he classes where we have ident ified are fully
independent of ot her classes and can operat e as independent ent it ies.
Note: For funct ions like Init iat eLoan and ApproveLoan, a ‘Loan’ obj ect might
be required. This however is not a breach of t he above st ep, because for doing
somet hing useful, obj ect s have t o int eract .
Even wit h t hese met hods, t he obj ect is fully independent as it does not depend
on Loan obj ect for it s exist ence. It j ust uses Loan obj ect s for one of it s met hod
(behavior).
Let us draw a barebones Class diagram wit h all t he classes ident ified wit h t he at t ribut es and
met hods along wit h t heir access specifiers specified (Refer t o Figure 5-1).
Figure 5-1: Classes with attributes, methods and their access specifiers identified
Step 7 and 8: The methods in the class should completely abstract the functionality. The
methods in the class should not be a force fit of procedural code into a class
We have ensured t hat we have met hods like Init iat eLoan, ApproveLoan and Accept EMI in
applicable classes, which are an abst ract ion of t he funct ionalit y of t he class wit hout exposing
t he complexit y of t he act ual funct ion inside!
Step 9: Inherit and extend classes from the base classes ONLY IF the situation has scope
for it.
Refer t o Figure 5-1. The ‘Employee’ class already has t he common met hods and variables
(EmployeeID, Email) t hat applies t o LoanAdvisor, BankManager and Teller classes.
Also, Init iat eLoan is a common fact or bet ween LoanAdvisor and BankManager.
Given t his informat ion, all t he classes ident ified can inherit from Employee. Also,
BankManager can inherit from LoanAdvisor. Refer t o Figure 5-2 for t he modified Class diagram
wit h all t he common at t ribut es and met hods isolat ed t o t he base class.
(PSOR\HH
(PSOR\HH,'LQW
(PDLOVWULQJ
*HW(PSOR\HH,'LQW
6HW(PSOR\HH,'
*HW(PDLOVWULQJ
6HW(PDLO
/RDQ$GYLVRU 7HOOHU
,QLWLDWH/RDQ $FFHSW(0,
%DQN0DQDJHU
$SSURYH/RDQ
Step 10: Define the relationships among the classes (“Has-A”, “Uses-A”)
We have already defined t he “ Is-A” relat ionships in t he previous st ep. There is no scope for
“ Has-A” or “ Uses-A” relat ionship here.
Step 11: Keep the number of classes in your application under check (Do not create any
unnecessary classes)
From t he Class diagram (Ref er t o Figure 5-2), we can observe t hat are no unnecessary classes.
27
Refactoring: The process of improving t he design or code in soft ware proj ect s (especially ones which
are having problems) by removing duplicat ion, improving readabilit y. This requires a lot of modificat ion
t o code and somet imes even complet e rewrit ing of code.
28
Framework: An implement at ion t hat provides a general solut ion t o some problem common t o many
applicat ions. A framework is usually refined t o address t he specific problem t hrough specializat ion or
addit ional t ypes or classes.
29
Application Programming Interface (API): A set of f unct ions used by an applicat ion program t o
provide access t o t he applicat ion’ s capabilit ies. Operat ing syst ems also use t he same concept t o
provide access t o t heir capabilit ies. Example: Win32 API is a set of funct ions provided by Microsoft
Windows t o provide access t o t he Windows operat ing syst em’ s feat ures.
By lat e 1990s, Obj ect Orient ed Programming languages had become mainst ream development
languages. The new languages also addressed some of t he common issues which programmers
encount ered in earlier OO languages like C++.
Example: The int erf ace KeyList ener is part of t he Java API. The int erf ace KeyList ener is used
by obj ect s t o list en t o any keyboard event s like a key get t ing pressed, or released.
Not ice t hat t he int erf ace is j ust a set of met hod signat ures and does not cont ain any body.
Any class can implement an int erf ace.
The class Test implement s of t he above int erf ace. In ot her words, t he class would provide
bodies f or t he met hods declared in t he above int erf ace. The code f or class Test would look
like t his:
public class Test implements KeyListener {
A class can implement more t han one Int erface. Int erfaces do not have complex synt ax like
Mult iple Inherit ance. Mult iple int erfaces can be implement ed in a class.
This concept is more useful and usable t han t he concept of Mult iple Inherit ance.
Newer programming languages like Java, C# do not support t he concept of Mult iple
Inherit ance. As an alt ernat e, int erfaces are provided in t hese languages.
Point s t o Remember:
• An Int erface is a set of met hod signat ures
• Int erface does not have a body
• Any class can implement more t han one int erface
• Older OO Languages like C++ do not support t he concept of int erface
In newer OO languages like Small Talk, Java, C#, however, all classes inherit from a class
called Obj ect . Whet her programmer specifies t his inherit ance explicit ly or not , all obj ect s
will have a common base class. Ref er t o Figure 6-1 f or an example.
This t echnique provides some common funct ionalit y t o all t he classes in t he programming
language. Using a common base class (or super class) also provides abilit y t o add new feat ures
t o all classes wit h a newer version of t he programming language. Such changes can be done
wit hout having t o make any changes t o t he code writ t en already.
6.3. Epilogue
Over t wo decades since t he 1980s, Obj ect Orient ed t echnology has come a long way. Over
t his t ime, many of t he concept s have also been refined. Many advanced and useful concept s
have emerged in t he newer programming languages like Java and C#. Some import ant and
proven concept s have been highlight ed in t his chapt er.
The programming languages have become simplified. However, t he complexit y of applicat ions
and size of code in applicat ions have also grown significant ly at t he same t ime.
Various Frameworks which provide a lot of built in ut ilit y classes and domain specific classes
have also emerged as a st andard part of many applicat ions. The key t o success of Obj ect
Orient ed Programming, t herefore also lies in t he abilit y t o underst and t he frameworks and
apply t he OO concept s while using t hem in real proj ect s. The concept s underst ood in t his
course can be used t o work wit h any framework.
This course provided t he basic underst anding of Obj ect Orient ed concept s, which are
universal across programming languages. It also provided a checklist for evolving an Obj ect
Orient ed design and guidelines t o refine t he design.
Cust omers approach t he Dispat chers30 at SpedFast count ers t o send shipment s. One cust omer
can send as many shipment s as required. The Dispat cher init iat es a shipment aft er t he
payment from t he cust omer.
Each shipment has a Shipment ID associat ed wit h it . A shipment also has a Recipient ’ s
address, priorit y, weight of t he shipment , shipping dat e and dat e of delivery. The amount is
calculat ed based on t he weight of t he shipment and priorit y. Current ly SpedFast provides
“ LOW, NORMAL and URGENT” priorit ies wit h different rat es on shipment s.
SpedFast also int ends t o have a Greet ing Shipment service for cust omers t o send Gift s for
celebrat ions. This is similar t o t he normal shipment s, but it also carries a “ Greet ing message”
from t he cust omer.
30
Dispatcher: The person who dispat ches shipment s in a post al organizat ion or courier company.
The t icket ing syst em addresses t he needs of t he met ro rail service of D-Rail bet ween t he cit y
and it s suburbs.
A Ticket ing Clerk at one of t he D-Rail count ers can issue t he following kinds of t icket s t o
commut ers:
One Time ticket: Used for one way t ravel. It has t o be used t he same day it is issued.
Return ticket: Used for t wo way t ravel. Onward j ourney has t o be done on t he dat e of
issue. However, t he ret urn j ourney can be done any t ime wit hin a week from t he dat e of
issue.
Multi-use ticket: Used for t raveling many t imes bet ween an origin and dest inat ion
st at ions (onward or ret urn). Mult i-use t icket s are available 10, 15 and 20 t rips
denominat ions, which are also specified in t he t icket . However t he t icket has an expiry
dat e which is t wo mont hs from t he dat e of issue. Every t ime t he t icket is used, one t rip is
deduct ed.
All t icket s have informat ion on t he origin and dest inat ion st at ions. A Ticket can be issued for
eit her a single commut er or a group of commut ers.
All t he t icket s issued are magnet ic t icket s which st ore t he ent ire t icket informat ion. This
informat ion will be verified by t he t icket reading machine at t he ent ry point s.
Problem Statement: Refer t o “ Sect ion 5.3 Best Pract ices in OO Design Met hodology” and
refine t he design depict ed in t he class diagram shown below.
7LFNHW
2ULJLQVWULQJ
'HVWLQDWLRQVWULQJ
*HW2ULJLQVWULQJ
6HW2ULJLQ
*HW'HVWLQDWLRQVWULQJ
6HW'HVWLQDWLRQ
0XOWLXVH7LFNHW
2QH7LPH7LFNHW
5HWXUQ7LFNHW 1XPEHU2I&RPPXWHUVLQW
1XPEHU2I&RPPXWHUVLQW
1XPEHU2I&RPPXWHUVLQW 'DWH2I,VVXH,VVXH'DWH
'DWH2I,VVXH,VVXH'DWH
'DWH2I,VVXH,VVXH'DWH ([SLU\'DWH([SLU\'DWH
*HW1XPEHU2I&RPPXWHUVLQW 5HPDLQLQJ7ULSVLQW
9DOLG8QWLO'DWH(QG'DWH
6HW1XPEHU2I&RPPXWHUV
*HW1XPEHU2I&RPPXWHUVLQW *HW1XPEHU2I&RPPXWHUVLQW
*HW'DWH2I,VVXH,VVXH'DWH
6HW1XPEHU2I&RPPXWHUV 6HW1XPEHU2I&RPPXWHUV
6HW'DWH2I,VVXH
*HW'DWH2I,VVXH,VVXH'DWH *HW'DWH2I,VVXH,VVXH'DWH
6HW'DWH2I,VVXH
6HW'DWH2I,VVXH
*HW9DOLG8QWLO'DWH(QG'DWH *HW([SLU\'DWH([SLU\'DWH
6HW9DOLG8QWLO'DWH 6HW([SLU\'DWH
*HW5HPDLQLQJ7ULSVLQW
6HW5HPDLQLQJ7ULSV
,VVXH'DWH
'D\LQW
0RQWKLQW
<HDULQW
*HW'D\LQW
6HW'D\
*HW0RQWKLQW
6HW0RQWK (QG'DWH ([SLU\'DWH
*HW<HDULQW 'D\LQW 'D\LQW
6HW<HDU 0RQWKLQW 0RQWKLQW
<HDULQW <HDULQW
*HW'D\LQW *HW'D\LQW
6HW'D\ 6HW'D\
*HW0RQWKLQW *HW0RQWKLQW
6HW0RQWK 6HW0RQWK
*HW<HDULQW *HW<HDULQW
6HW<HDU 6HW<HDU
Glossary
Abstract Data Type: A set of dat a values and associat ed operat ions t hat are precisely specified
independent of any part icular implement at ion.
Application Programming Interface (API): A set of funct ions used by an applicat ion program t o provide
access t o t he applicat ion’ s capabilit ies. Operat ing syst ems also use t he same concept t o provide access
t o t heir capabilit ies. Example: Win32 API is a set of funct ions provided by Microsoft Windows t o provide
access t o t he Windows operat ing syst em’ s feat ures.
Assembly Language: Similar t o machine language, but provides names for numeric inst ruct ions present
in t he machine language, making it easy for t he programmer.
Attribute: A charact erist ic associat ed wit h a person or t hing; In Obj ect Orient ed t echnology, ref ers t o
t he member variables of a class.
Black Box: When t he exact inner workings of a given syst em aren’ t known out side, it is known as Black
Box. Such syst ems are only charact erized only by t he behavior t hey exhibit ext ernally.
Boolean Logic: A logic syst em developed by Brit ish mat hemat ician, Prof. George Boole. This logic
applies t o variables which have only t wo values (0 or 1 – Binary values).
Built-in Data Type: Dat a t ypes t hat are already available in a programming language. Usually refers t o
t he primit ive dat a t ypes. However, some high level languages may have some complex dat a t ypes also
built in t o t he language.
Circuit (Or Electronic Circuit): A group of elect ronic component s connect ed t o perform a specific
funct ion.
Data Type: A named cat egory of dat a t hat is charact erized by a set of values, t oget her wit h a way t o
denot e t hose values and a collect ion of operat ions t hat int erpret and manipulat e t he values. See al so:
Buil t -in Dat a Type, Primit ive Dat a Type.
Developer Productivity: A measure of t he amount of qualit y code t hat can be writ t en by a developer
in a given amount of t ime.
Digital Circuit: A circuit which operat es in t he manner of a swit ch, eit her "on" or "off" (0s and 1s). All
comput ers are built on digit al circuit s.
Digital Electronics: The branch of elect ronics dealing wit h informat ion in binary form (Zeroes and
Ones).
Equated Monthly Installments (EMI): (In Banking) it is a mont hly inst allment paid by t he person who
has availed a loan t o clear t he loan. EMI consist s of Part of t he principal amount and t he int erest
incurred on t he loan.
Floating Interest Rate: For some t ypes of loans, banks offer int erest rat e which keeps changing wit h
t ime, based on t he economic sit uat ion.
Framework: An implement at ion t hat provides a general solut ion t o some problems which are common
t o many applicat ions. A f ramework is usually refined t o address t he specific problem t hrough
specializat ion or addit ional t ypes or classes.
Gate: A comput er circuit wit h several input s but only one out put t hat can be act ivat ed by part icular
combinat ions of input s
Global Variables: The variables t hat are declared out side any funct ion body. These variables exist for
t he ent ire life-cycle of t he program. Global variables can be accessed from anywhere wit hin t he
program.
Hierarchy: A classification of relationships in which each item except the top one is a specialized form of
the item above it. Each item can have one or more items below it in the hierarchy.
Local Variables: The variables t hat are declared wit hin a funct ion body. Their scope is limit ed t o
wit hin t he funct ion. Local variables cannot be accessed out side t he funct ion.
Machine Language: Machine language is t he language which a Cent ral Processing Unit (CPU) of a
comput er underst ands and consist s only of numbers.
Modularity: The propert y of a syst em t hat has been decomposed int o a set of cohesive but loosely
coupled modules.
Primitive Data Type: Simple dat a t ypes like int egers, charact er, float ing point numbers support ed by
most programming languages.
Real Life Data: Dat a t hat is used as part of day t o day life. Examples: Dat e, Address of a person, Bank
account det ails, Salary det ails of a person, Order det ails in a business t ransact ion et c.
Refactoring: The process of improving t he design or code in soft ware proj ect s (especially ones which
are having problems) by removing duplicat ion and improving readabilit y. This requires a lot of
modificat ion t o code and somet imes even complet e rewrit ing of code.
Spaghetti Code: Spaghet t i code refers t o t he code where t he flow becomes very convolut ed especially
when t here are mult iple developers working on t he same code. This happens due t o frequent
modificat ion of code wit hout analyzing t he impact .
Teller: An employee of a bank who receives and pays out money (also known as cashier in some
count ries)
Index
A D
Abst ract Base class ................................ 36 Derived Class ....................................... 31
Abst ract class....................................... 36 Design Met hodology ............................... 44
Abst ract Met hods............................... 36
Abst ract Met hods .................................. 36 E
Abst ract ion.......................................... 11 Encapsulat ion....................................... 13
examples......................................... 11
Access Specifiers................................... 16 G
Prot ect ed ........................................ 33
Aggregat ion ......................................... 28 Generalizat ion...................................... 35
Approach t o design ................................ 44
H
Best Pract ices................................... 50
Associat ion .......................................... 29 Has-A................................................. 28
B I
Base Class ........................................... 31 Informat ion Hiding................................. 10
Behavior ............................................... 9 Inherit ance.......................................... 31
Mult ilevel ........................................ 33
C Mult iple .......................................... 34
Child Class .......................................... 31 Inherit s from........................................ 32
Class.................................................. 16 Inst ance ............................................. 19
Abst ract class ................................... 36 Int erface ............................................ 52
Access Specifiers ............................... 16 Is-A ................................................... 31
Aggregat ion relat ionship ...................... 28
K
examples......................................... 17
Has-A relat ionship.............................. 28 Kind-Of ......................................... 26, 31
Implement at ion................................. 18
Inst ance .......................................... 19 M
Member Funct ions.............................. 16 Member Funct ions ................................. 16
Member Variables .............................. 16 Member Variables.................................. 16
Met hods .......................................... 16 Message Passing.................................... 14
Part -Of relat ionship............................ 28 examples......................................... 15
Uses-A relat ionship............................. 29 vs Procedural Call .............................. 21
vs Obj ect ......................................... 21 Met hod Overloading ............................... 38
Class Diagram....................................... 22 Met hod Overriding................................. 40
Associat ion ...................................... 29 Modularit y........................................... 10
Has-A ............................................. 28 Mult ilevel Inherit ance............................. 33
Inherit ance ...................................... 32 Mult iple Inherit ance............................... 34
Mult ilevel Inherit ance ......................... 33 Mult iplicit y .......................................... 30
Mult iple Inherit ance ........................... 34 One t o Many ..................................... 30
Part -Of ........................................... 28 One t o One ...................................... 30
Classes
Kind-Of relat ionship ........................... 26 O
Mult iplicit y of relat ionships .................. 30
Relat ionships.................................... 25 Obj ect ................................................. 8
Common Base Class ............................... 53 Behavior............................................ 9
Common Super Class .............................. 53 examples........................................... 8
St at e ................................................ 9
vs Class........................................... 21