0% found this document useful (0 votes)
31 views

OOPS

Uploaded by

SHIVAM PANDEY
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)
31 views

OOPS

Uploaded by

SHIVAM PANDEY
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/ 32

Object-oriented Programming Concepts_SG/12-M06-V01

Copyright ©NIIT. All rights reserved.

This product or document is protected by copyright and


distributed under licenses restricting its use, copying,
distribution and decompilation. Please view “Mark of
Authenticity” label to establish proper licensed usage. No
part of this document may be copied, reproduced, printed,
distributed, modified, removed, amended in any form by
any means whether electronic, mechanical, digital, optical,
photographic or otherwise without prior written
authorization of NIIT and its authorized licensors, if any.
Information in this document is subject to change by NIIT
without notice. The names of companies, products, people,
characters, and/or data mentioned herein are fictitious and
are in no way intended to represent any real individual,
company, entity, services, product or event, unless
otherwise noted.
All products are registered trademarks of their respective
organizations.
All software is used for educational purposes only.

Disclaimer: The documents and graphics on this


courseware could include technical inaccuracies or
typographical errors/translation errors. Changes are
periodically added to the information herein. NIIT may
make improvements and/or changes herein at any time.
NIIT makes no representations about the accuracy of the
information contained in the courseware and graphics in
this courseware for any purpose. All documents and
graphics are provided “as is”. NIIT hereby disclaims all
warranties and conditions with regard to this information,
including all implied warranties and conditions of
merchantability, fitness for any particular purpose, title
and non-infringement. In any event, NIIT and/or its
licensor(s)/supplier(s) shall not be liable to any party for
any direct, indirect, special or other consequential
damages for any use of the courseware/translated
courseware, the information, or on any other hyper linked
web site, including, without limitation, any lost profits,
business interruption, loss of programs or other data on
your information handling system or otherwise, even if
NIIT is expressly advised of the possibility of such
damages.
Due to the dynamic nature of the internet, the URLs and
web references mentioned in this document may be (are)
subject to changes, for which NIIT shall not hold any
responsibility.
Conventions
About This Course
Convention Indicates...
Note
Prologue
Hint
Description
This course introduces you to the object-oriented Animation
methodology. It discusses the features and advantages of
object-oriented programming. In addition, it explains the
considerations that need to be kept in mind while Just a Minute
designing an object-oriented program.

Streaming Media
Rationale
Object-oriented concepts form the base of all modern Let’s Practice
programming languages. Understanding the basic concepts
of object orientation helps a developer to use various
modern day programming languages, more effectively.
The course is applicable to students who want to enter the
world of object-oriented programming. This course
provides a strong foundation that will help the student to
learn any object-oriented programming language with
ease.

Objectives
After completing this course, the student should be able to:
q Identify the basics of object orientation
q Identify the features of object orientation
q Design object-oriented programs

Entry Profile
The students who want to take this course should have:
q Basic knowledge about the various parts of the
computer and should know the basic difference
between hardware and software.
q The ability to devise step-by-step procedures to
solve a problem by using flowcharts, algorithms,
and pseudocodes.

Exit Profile
After completing this course, the student should be able to:
q Identify the fundamentals of object-oriented
programming.
Chapter 1
Introduction to the Object-oriented
Approach
In order to survive, businesses need to incorporate
complex and interrelated processes in their working. Due
to this complexity and interdependency among processes,
the code written to implement the processes becomes
complex and difficult to manage. In order to reduce this
complexity and improve maintenance, you can use a
programming paradigm that can break down a problem
into smaller units, which can be easily handled. Object-
oriented Programming (OOP) is one such approach.
This chapter introduces the object-oriented methodology
and discusses the concepts of objects, classes, messages, The Foundation of Object Orientation
and methods. The chapter also explains the advantages of
Object orientation involves splitting the software system
object orientation.
into smaller components and arranging these in a
Objectives hierarchy. To understand the concept of an object, let us
take the example of an architect, John, who is working on
In this chapter, you will learn to: a project to build a conference hall for a school. To build
q Identify the object-oriented methodology the conference hall, John will start by building a room and
q Identify the advantages of object orientation defining its boundaries and features, such as the
dimensions and colors of walls. Next, he will put together
other components, such as chairs, tables, telephones,
Overview of Object-oriented projection screen, and books, in the hall. These
components, such as room, chairs, and tables, which John
Methodology used to build the conference hall, are the objects of a real-
In today’s competitive world, it is important to develop life scenario and are similar to the objects in the object-
simple and speedy solutions that can be applied instantly oriented paradigm.
to varied requirements. This has resulted in the creation of Similarly, in OOP, a program is broken into independent
different, and sometimes, complex software systems. reusable chunks known as objects, which can be integrated
Though complexity of a software system cannot be to form a complete program. These objects can interact
avoided altogether, there are ways to ensure that this with each other by sending and receiving messages. A
complexity does not become a stumbling block to the program that uses OO technology is primarily a collection
smooth functioning of the software. One way of reducing of objects. In other words, objects are the building blocks
the complexity is to use the concept of object orientation. of an OO program.
Let us now discuss the following terms associated with
object orientation:
Defining Object Orientation q Objects
Object orientation is a software development methodology q Classes
that is based on modeling a real-world system. An object q Messages and methods
is the core concept involved in object orientation. It is the Objects
representation of a real-world entity or concept. For An object literally means a thing that can be presented
example, an employee, a window, a car, or a bird can be physically. In other words, an object is a touchable entity
modeled as objects. An Object-oriented (OO) model can that may show some well-defined behavior. For example,
be considered as a collection of objects and their inter- consider the following statements in relation to a tennis
relationship. ball:
q A tennis ball is a touchable entity, with a visible
boundary in physical terms.
q A tennis ball has a specific defined purpose (such method by sending a message to the object.
as bouncing). An object can be associated with multiple methods, each
q A tennis ball can be acted upon (for example, it having a set of instructions. Each of these methods has a
can be hit with a racquet or can be tossed around). unique purpose and helps implement a particular behavior
However, the definition of an object is not limited to of the object.
something that can be seen, held, and touched, such as a
tennis ball or a chair. For the purpose of software
development, a non touchable thing can also be defined as
an object. For example, in a car racing video game, the car
is an object. You can drive the car, turn the car, and stop
the car when needed.
According to the famous software architect, Grady Booch,
an object has the following characteristics:
q It has a state that is indicated by a set of attributes
and their values.
q It may display behavior that is reflected by the
change of its attributes over a period of time.
q It has a unique identity, which distinguishes it
from other objects.
Now, let us see how a car fulfills these requirements to
become an object. A car has the following characteristics:
q A car can have various states, such as moving and
stationary.
q It can show various behaviors, such as
Classes
Look at the world around you. It is full of objects of
accelerating, decelerating, or turning.
q It also has an identity, such as a unique various shapes, sizes, colors, and behaviors. Based on
these characteristics, these objects can be classified into
registration number.
The following figure depicts the characteristics of a car. different groups. These groups are called classes. Classes
act as the blueprint to create objects. An object belonging
to a given class is called an instance of the class. A class
includes attributes and methods that act on those
attributes.
For example, in case of a class of students, all the students
have the same attributes, such as name, ID, and age. They
have the same type of behavior, such as attending classes,
taking exam, and obtaining marks. Therefore, they can be
grouped together to form a class, Student, where each
State, Behavior, and Identity of a Car Object student is a distinct object of this class. The following
Two objects may have the same behavior and state, but figure shows the Student class and its objects.
they can never have the same identity. The identity of an
object does not change in its lifetime. For example, two
tennis balls may have the same color, be made of the same
material, have the same weight, and display the same
behavior. However, they will have distinct identities (for
example, one ball will have the factory seal number
‘A189735’ and the other ‘S660794’).
OOP combines user-defined data and instructions that act
on that data into a single entity called an object. The data
stored within an object represents the state of the object. In
OO programming terminology, this data is called
attributes.
The instructions associated with the object form the
behavior of the object. The behavior of an object is what
the object can do. In OO programming terminology, these
behaviors are contained in methods; and you can invoke a
The Student Class
In the preceding figure, the Student class has two
objects, Student1 and Student2, which store details
of two students, Sam and John, respectively. In OOP, a
separate copy of attributes is maintained for each object,
but the same copy of methods can be shared among them.
Here, the attributes, such as ID, Name, and Age, are
different for both the students, but the methods,
attendClass, takeExam, and obtainMarks are
same.
You can access the attributes and methods of an object by
using the dot (.) operator. For example, you can access the
attribute, ID, of Student1 by using the dot operator, as
shown in the following statement:
Student1.ID
Similarly, you can access the obtainMarks method of
Student1 by using the dot operator, as shown in the
following statement:
Student1.obtainMarks() Let’s Practice
Accessing a method to invoke a particular behavior of an
object is known as calling a method.

In the preceding method call, notice the use of


parenthesis after the method name. Calls to methods are
always followed by a pair of parenthesis. You will learn more
about methods in the subsequent chapters.
Messages and Methods
Objects do not exist alone. They communicate with other
objects. This communication takes place through
messages. Grady Booch has defined behavior as:
“Behavior is how an object acts and reacts, in terms of its
state changes and message passing.”
Consider the example of a man using an escalator. Here
we have two objects, man and escalator. When the man
steps on the escalator, the escalator starts moving. As soon
as the man gets down the escalator, it stops.
The behavior of the escalator object is dependent on the
message given by the man. For example, when the man
steps on the escalator, it receives a message “Stepping up”. Advantages of Object Orientation
The escalator responds by moving. Therefore, behavior In recent years, object-oriented programming has become
(also called method in the object-oriented methodology) is very popular. It has several advantages, which make it
simply a set of actions taken in response to a message easier for programmers to develop applications using
received by the object. OOP. Some of the advantages of OOP include:
q Realistic modeling
Methods are also known as functions or subroutines. q Reusability
q Modularity
q Flexibility to change
q Information hiding

Realistic Modeling
Because you live in a world of objects, it logically follows
that the object-oriented approach models the real-world
more accurately. The object-oriented approach allows you modifications in the required object without affecting
to identify entities as objects having attributes and functionality of the other objects.
behavior. Attributes and behavior typically depict how the
object acts and reacts.
For example, every car is an object belonging to the class,
Car. Each car has the same attributes, such as color and
power, and displays same behavior such as accelerating or
decelerating.

Reusability
An object exists as a stand-alone entity that can be used in
any relevant context. Therefore, it is a reusable
component. For example, if you have a chair, you can use
it in an office, classroom, and garden.
OOP enables you to consider a real-world entity as an
object. After objects are created, they can be placed in
libraries. Objects in these libraries can be reused in other
programs with similar requirements. OOP languages also
offer some built-in libraries. These libraries consist of a set
of pre-defined objects that can be used by all programs.
In the software industry, using existing classes or objects
Flexibility to Change
from other applications reduces not only the effort of The object-oriented approach allows systems to evolve.
recreating the components, but also the chances of When a change is needed, the old system need not be
introduction of errors in various modules. After integrating completely abandoned.
all the modules, a consolidated system can be created that Consider the example of JoyToys, Inc., which is a
has all the components that can be reused across the company that manufactures toys for children in the age
modules. The benefit of reusability translates to savings in group of 1 to 12 years. Its toy cars are popular with
time and effort, which in turn results in cost effectiveness. children because of their attractive colors, shapes, and
sound.
For the last two years, the company had no complaints
about the design of the toy car. However, with
advancement in technology and increasing competition,
the manufacturers now want to stop manufacturing the old
car because the market requirements have changed. They
want the company to manufacture a car that has flashing
lights and is remotely controlled.
In the object-oriented system, this requirement does not
require the new car to be built from the scratch. The new
features can be easily added to the old toy car without
changing its color, shape, and sound, as shown in the
following figure.

Modularity
Another advantage of OOP is its modularity. This means
that an object can be maintained independently of other
Illustration of Flexibility to Change
objects. All these objects are independent of each other
In the context of software systems, you can create new
and are maintained separately. You can make
classes by adding new features to an existing class. This
trait of object-oriented programming, where a new class is
created that inherits all the features of an existing class and
has some features of its own, is known as inheritance.
The ability of a class to inherit features from another class
makes object-oriented programs extensible. When a
change is suggested in an existing system, the old system
need not be completely abandoned to build a new one
from scratch. Changes can be incorporated into the already
existing system. This feature of object-oriented
methodology is known as extensibility. Extensibility
makes programs flexible to changes and helps in easy
maintenance of the software.

Let’s Practice

Information Hiding
Objects provide the benefit of information hiding. Only a
limited access to information is provided to the user. The
attributes and the behavior are hidden within the class.
This is because the user is required to know only about the
implementation of the class and not the internal details of
the class.
For example, when you use a phone, you just need to Summary
know how to operate it; you do not need to know the
working process of the phone. This process is, therefore, In this chapter, you learned that:
hidden from the user. Similarly, when you play a car q According to the object-oriented approach,
racing game on a computer, you only need to know how to systems consist of component objects that interact
turn, accelerate, or decelerate the car. You do not need to with each other.
know how these actions actually happen or what q An object possesses the following characteristics:
instructions are given to the computer to make these xState
actions happen. All these details are, therefore, hidden xBehavior
inside a class. xIdentity
The class provides only an interface that enables you to q A class consists of a set of objects that share a
invoke these actions. The implementation of these actions common structure and behavior.
is hidden from the user. This helps in simplifying the q An object is defined as an instance of a class.
development of programs and ensures that the data q If an object desires an action from another object,
belonging to a class is not accidently accessed or modified it sends a message to that object.
by another class. q The object that receives the message is called the
receiver, and the set of actions taken by the
receiver constitutes the method.
q The advantages of the object-oriented approach
are:
xRealistic modeling
xReusability
xModularity
xFlexibility to change
xInformation hiding

Reference Reading
Overview of Object-oriented
Methodology

Reference Reading: Books Reference Reading: URLs


Matt Weisfeld, The Object- http://
Oriented Thought Process www.csharphelp.com/2007/
03/objects-classes-in-c/

Advantages of Object Orientation

Reference Reading: Books Reference Reading: URLs


Bertrand Meyer, Object- http://codebetter.com/blogs/
Oriented Software raymond.lewallen/
Construction C# archive/2005/02/08/50663.a
spx

http://
eprints.ecs.soton.ac.uk/857/
3/html/node3.html
Chapter 2
Exploring the Features of Object
Orientation
The implementation of object-oriented components makes
complex programs easier to understand, allows reusability
of code, and reduces the amount of maintenance required.
All this becomes possible because of certain features
provided by Object-oriented programming, such as
encapsulation, inheritance, abstraction, and polymorphism.
This chapter explores these features of the Object-oriented
programming languages.

Objectives
Information Hiding
In this chapter, you will learn to:
q Identify the concept of encapsulation Let us consider an example. While watching a television,
q Identify the concept of inheritance you do not need to know how the remote control sends the
q Identify the concept of abstraction signals to the television for changing channels. You only
q Identify the concept of polymorphism need to know how to control the television by using a
remote. In other words, the internal working of the remote
control has been encapsulated. Therefore, encapsulation
Exploring the Concept of helps implement information hiding or data hiding
because it involves hiding many of the details of an object
Encapsulation from the user.
One of the main advantages of using objects is that objects In the context of object-oriented programming,
provide independence among various components of a information hiding is a technique of limiting the access to
program. They provide you the flexibility of modifying variables, methods, and classes in a program. It allows the
one part of a program without affecting the other. This developer to prevent access to non-essential details of an
flexibility is a feature of the object-oriented programming, application. The users are allowed to access only the data/
called encapsulation. methods required by them. This helps a programmer to
hide the implementation details of an object from a user of
the object. Therefore, anyone who wants to use the object
Defining Encapsulation for implementing a particular functionality, only needs to
know how to invoke that functionality, without worrying
Encapsulation literally means to enclose in or as if in a
about how to implement that functionality.
capsule. Encapsulation is defined as the process of
Consider the example of a tennis video game where the
enclosing data and methods within a logical package,
virtual player hits the ball with a racquet and the ball goes
called class. It is the mechanism that binds together data
to the other side of the court. The coding for the motion of
and related code in an object to make each object
the ball or the racquet is encapsulated and hidden inside
independent of other objects. Encapsulation leads to the
the Ball class or the Racquet class. Therefore, any
important concept of information hiding, which helps to
keep the data belonging to an object safe from outside programmer who needs to use a Racquet object in a
misuse. program, only needs to know which method of the
Racquet object needs to be invoked to move the racquet
in a particular direction. The programmer does not need to
know the complications of the programming involved in
moving the racquet.
In other words, the interface of these objects is separate
from their implementation. Encapsulation and data hiding
help you separate the interface of an object from its
implementation. This enforces privacy of data. Restricted
access to the members of an object stimulates The following figure depicts the accessibility of the public
programmers to write specialized methods for performing members of a class from outside the class.
operations on hidden members of the class. Users can be
granted access only to these specialized methods and not
to the hidden members of the class.

An interface defines the fundamental means of


communication between objects. Implementation refers to
specifying the steps to perform a particular task.
Information hiding is implemented in programs with the
help of access specifiers.

Accessibility of Public Members of a Class


In the preceding figure, you have three classes: Circle,
Square, and Rectangle. All the attributes of the
classes are declared private, whereas all the methods are
declared public. Here, the public methods of the Square
class, getArea and getPerimeter, are accessible
from the Circle class and the Rectangle class.
The Private Access Specifier
The private access specifier allows a class to hide its
member variables and member methods from other
classes. Therefore, the private members of a class are not
visible outside a class. They are visible only to the
methods of the same class. Therefore, the data is hidden
and cannot be altered by any method other than the
member methods of the class.
The following figure depicts the accessibility of the
private members of a class from outside the class.
Access Specifiers
An access specifier defines the scope of a class member.
The scope of a class member refers to the portion of the
application from where the member can be read and/or
written to. It is also known as the accessibility of a
member.
A program can have one or more classes. You may want
some members of a class to be accessible to other classes.
However, you may not want some other members of the Accessibility of Private Members of a Class
class to be accessible outside the class. In the preceding figure, the private attribute, size, of the
It is the privilege of the programmer to decide the use of Square class is not accessible from the Circle class or
access specifiers to implement information hiding. You the Rectangle class. However, methods within the
use various types of access specifiers to specify the extent Square class can access the size attribute.
of the visibility of a class member. The basic types of
The Protected Access Specifier
access specifiers are:
The protected access specifier allows a class to hide its
q Public member variables and member functions from other
q Private classes, except those classes that inherit their features from
q Protected the class. The protected access specifier becomes
The Public Access Specifier important while implementing inheritance.
The public access specifier allows a class to expose its
member variables and member methods to other classes.
Any member that is declared public can be accessed from Inheritance will be discussed in detail in the next
outside the class across applications. section.
approach is code reuse. Inheritance is a process of
deriving new classes from existing classes. The existing
class is called the base class or super class and the
inherited class is called the derived class or sub class. The
derived classes contain all the attributes and behaviors of
the existing classes, plus their own attributes and
behaviors.
For example, if you have a Student class that consists
of the basic characteristics of students, such as name, date
of birth, and gender. You can extend the functions of the
Student class to a day scholar, which, in addition to the
characteristics of the Student class, contains its own
features, such as locker number and residential address.
The parent-child relationship between classes can be
represented in a hierarchical view, often called as a class
tree view. The class tree view starts with the super class,
while derived classes become more specialized further
down the tree.
Let’s Practice The following figure shows the concept of a super class
and a sub class.
Richard wants to create a class named Shape. The
Shape class consists of the following variable and
method:
q Variable: Side
q Method: Area()
Now, he wants to inherit a class named Rectangle from
the Shape class and modify the Area() method. In
addition, he wants to ensure that no other class should
access the Area() method, except the classes that are
inherited from the Shape class. Which of the following
access specifiers should Richard use for the Area()
method of the Shape class, in order to implement the
preceding functionality?
a. public
b. private
c. protected

Concept of a Super Class and a Sub Class


Exploring the Concept of Inheritance A super class provides data (instance variables) and
An existing object can be used to create a similar object. functions (methods) to be inherited by the sub class. It can
For example, you have a simple wooden chair, but you also be called a base class or parent class. The super class,
need a chair with a headrest. You do not need to create a or parent class, contains all the attributes and behaviors
new chair because you can easily add a headrest to the that are common to classes that inherit from it.
existing chair. A sub class or child class is a class that inherits attributes
Similarly, object-oriented programming enables you to and behavior from a super class. A sub class can also be
extend existing classes to create new classes that have called a child class or derived class. It is a more specific
some features in common with the existing ones. This is version of its super class. Each instance of a derived class
achieved by using the inheritance feature of object- includes its own attributes and all the attributes of the base
oriented programming. class. Therefore, the derived class has a larger set of
attributes than its base class. Some or all the attributes of
the derived class can be modified.
Defining Inheritance Inheritance avoids redundancy in code and enables easy
maintenance. Any change made to the base class
One of the most powerful characteristics of the OO automatically changes the behavior of its sub classes. In
this case, the sub classes automatically inherit the new
behavior.
The following examples define inheritance between
classes:
q A scientific calculator is an extended form of a
simple calculator. Here, calculator is the super
class, and scientific calculator is the sub class.
q A chair is a type of furniture but has its own
features other than the general features of
furniture. Therefore, furniture is the super class,
and chair is the sub class.
q Employees in an organization are identified with
their own features but can be categorized as
permanent or temporary. Here, employee is the
super class and permanent employees and
temporary employees are the child classes.

A sub class inherits only the public and protected


members of its super class.

Single Inheritance
In the preceding figure, Dog is the child class that inherits
from the parent class, Animal.
Multiple Inheritance
Some object-oriented programming languages allow a
child class to inherit from more than one parent class. This
is called multiple inheritance. The following figure depicts
an example of multiple inheritance.
Types of Inheritance
Inheritance is of various types. These include:
q Single inheritance
q Multiple inheritance
q Multi-level inheritance
Single Inheritance
Single inheritance is a common form of inheritance. In this
case, a child class has only one parent class. The following
figure depicts an example of single inheritance.
Accessibility of Protected Members in
Inherited Classes
Protected members of a class (members declared with the
protected access specifier) are accessible only to the
Multiple Inheritance methods in the same class or to methods in the classes
In the preceding figure, class Q inherits from two classes, derived from that class.
class A and Z. Class Q inherits attributes and behavior of The following figure depicts the accessibility of the
class A and Z, and also has some attributes and behavior of protected members of a class from outside the class.
its own.
Multi-level Inheritance
Multi-level inheritance is the enhancement of the concept
of inheritance. When a sub class is derived from a derived
class, the mechanism is known as multi-level inheritance.
The derived class is called sub class or child class for its
parent class; this parent class works as the child class for
the class from which it is derived. Multi-level inheritance
can go up to any number of levels. The following figure
depicts an example of multi-level inheritance.

Accessibility of Protected Members of a Class


In the preceding figure, the Dog and Bird classes are
derived from the Animal class. The protected attribute,
age, defined in the Animal class is accessible from the
method of the Animal class as well as it is also
accessible from the methods of the derived classes, Dog
Multi-level Inheritance and Bird. However, any other class that is not derived
In the preceding figure, the Cats class is a sub class of from the Animal class cannot access the protected
the Mammals class and a super class of the Lions, member of the Animal class.
Tigers, and Leopards classes.
q You cannot declare an abstract method outside an
abstract class.
q A class, which is derived from an abstract class,
must override all the methods of the abstract
class.
q If a derived class does not implement all the
abstract methods in the base class, then the
derived class must also be specified as abstract.

Abstract Classes and Methods


At times, you may want to create a super class, which does
not have a concrete implementation. For example you can
define a class, Shape, and declare a method, draw, in it.
Here, it is not clear what shape the method will draw.
Therefore, providing an implementation of the draw
method in the Shape class is not required. You can derive
from this class to create the Square and Circle
classes, which can provide implementation of the draw Virtual Functions
method. To implement this concept, you need to declare
the Shape class as abstract. When you want to provide a different implementation to a
An abstract class is a class that is incomplete and cannot function in a sub class than the one defined in the super
be used directly. Abstract classes contain abstract methods, class, you can define the function as virtual in the super
which can be implemented by the derived classes. You class. Virtual functions do not make overriding
cannot create an instance of an abstract class to use its compulsory, as in case of abstract functions, but give the
member functions. However, you can override the choice to the user. The functionality of the virtual function
methods of the abstract class in the derived class and can be modified by the inherited class according to
provide a new functionality to them. requirement.

A method declared in a base class can be redefined in


a derived class to provide it a different functionality. This
process is known as method overriding.
When you create derived classes, you provide specialized
functionality to the base class. Therefore, an abstract class
only defines abstract variables and methods, and their
implementation is given by the derived classes of the
abstract class.
Abstract methods are methods without any body. The
implementation of an abstract method is done by the
derived class. When a derived class inherits an abstract
method from an abstract class, it must override the abstract
method to provide it a new functionality.
There are certain rules governing the use of an abstract
class. These include:
q You cannot create an instance of an abstract class.
of concern to the system in question are included in the
Let’s Practice class and the irrelevant attributes are excluded.
Before designing a class, you should consider different
layers of abstraction. Only the essential details should be
defined at the abstract layer, which can form the super
class. The sub classes of the super class can be further
specialized by adding more details.
Let us consider the layers of abstraction, as shown in the
following figure.

Exploring the Concept of Abstraction


To understand the concept of abstraction, let us consider
an example. Let us assume you are a very good-looking,
humorous, and intelligent person. You may also have
several other qualities; for example, you may be an
excellent guitarist, a good swimmer, and a loving son/
daughter.
However, for a person who has to grant you a driving
license, all of these qualities will not be of any interest.
That person will only be interested in knowing whether
you are more than 18 years or not, whether you know the
Layers of Abstraction
traffic rules, and whether you can drive well. In other
In the preceding figure, the Vehicle class forms the first
words, this person will focus only on the essential
characteristics in you that suit his/her requirement. All the layer of abstraction. Every vehicle has some similar
other wonderful things about you that are not directly characteristics, such as color, and power, and the ability to
relevant will be ignored. be steered. So, in the first layer of abstraction, the
Vehicle class includes attributes, such as color and
In OOP, programmers often ignore all but the relevant data
power, and a method named steer. However, various
about an object in order to reduce complexity and increase
efficiency of software applications. This process of types of vehicles may have some additional attributes and
presenting only the relevant data in a program is called methods. These attributes and methods have been defined
abstraction. in the classes, Airplane and Ship, derived from the
Vehicle class. In addition, various types of vehicles will
have different ways to implement the steer method.
Defining Abstraction Therefore, it is pointless to implement this method in the
Vehicle class. You can provide this implementation in
Abstraction is the process of reducing the information the Airplane and Ship classes, each of which will
content of a concept or phenomenon in order to retain have its own implementation of the method.
information that is relevant for a particular purpose. This The Ship class is abstracted further to include only the
helps to simplify things by isolating only what is relevant
essential characteristics of a ship. Therefore, it forms the
for a particular purpose.
next level of abstraction. The classes, PassengerShip
In OOP, abstraction forms the basis of building classes. To
and CargoShip are derived from the Ship class and
build classes, a set of similar objects are observed and
include additional attributes of their own.
their common attributes are identified. Next, the attributes
Let’s Practice
Derrick and Samantha went to the car showroom to buy a
new car. The salesman of the showroom welcomes them
and explained various features of all the car models
available in the showroom, such as mileage, engine power,
automatic gear system, fogger-defogger, central/child lock
facility, and power steering. However, sales person does
not explain anything about the internal working of the cars
available there.
Which of the following concepts of the object-orientation
is implemented in the preceding scenario?
a. Inheritance
b. Information hiding
c. Encapsulation
d. Abstraction

Benefits of Abstraction Exploring the Concept of


Abstraction has various advantages, some of which are: Polymorphism
q It reduces complexity.
The term polymorphism was derived from the Greek
q It helps in retaining the same interface for
implementing different behaviors. words, poly (meaning many), and morphs (meaning
forms). Polymorphism is the ability to allow a function to
Abstraction deals with providing only the essential details
to the users. So, it helps to reduce the complexity of exist in different forms. For example, a person can react
differently to various situations. Therefore, different
software systems, where a user is required to know only
the functionality provided by an abstraction without being moods of a person, depending upon the situation he is in,
depict polymorphism.
concerned about the complexity of its implementation.
Through abstraction, you can implement multiple classes In object-oriented methodology, it is possible for an entity
that can have the same set of methods and attributes, but to have more than one form, depending upon the context
the internal working details of the classes can be different. in which it is used. This property of OOP, which enables
one entity to be used differently for different types of
For example, in case of the Vehicle class, both the
actions, is called polymorphism.
Airplane and the Ship classes have the same method,
steer, but the implementation of this method is different
in the two classes. Techniques to Implement
Polymorphism
Some techniques to implement polymorphism in an
object-oriented program are:
q Method overloading
q Operator overloading
q Method overriding
Method Overloading
Consider an example, where you need to determine the
total marks of a student in two subjects. The following
figure depicts the attributes and methods of the Student
class.
methods are different because the data type of
their parameters is different.
q The sequence of the parameters. Consider the
following methods:
Display(numeric Num1,Character
Message)
Display(Character Message,numeric
Num1)
In the preceding pseudocode segment, the two
methods are different because their parameters
are specified in a different order.
Attributes and Methods of the Student Class Therefore, overloaded methods must differ in the type,
The addMarks method takes the marks obtained by a number, and/or sequence of their parameters. The return
student in two subjects as parameters and calculates the type of the overloaded methods can be same or different.
sum of the values passed as parameters. Now, consider a It is not considered by the compiler to distinguish between
situation, where some of the students have enrolled for overloaded methods.
two courses, whereas others have enrolled for three
courses. In such a situation, you need to create two
methods, one that accepts marks of two subjects as Some methods return a value when they are called to
parameters and the other that accepts marks of three perform a specific task. The return type specifies the data
subjects as parameters. type of the value returned by the method. You will learn more
about methods in the next chapter.
Method overloading (also called function overloading)
allows you to assign the same name to two methods that Operator Overloading
perform similar function, but take different number or type In addition to methods, operators can also be overloaded.
of parameters. Therefore, in the preceding example, you Operators can be overloaded in order to perform special
can create another method, named addMarks that functions with respect to a class. With the help of operator
accepts marks of three subjects as parameters, as shown in overloading, standard operations, such as +, -, and *, can
the following figure. be applied on the objects of the class.
Consider an example of the Height class that has two
attributes, feet and inches. Suppose you have two
objects of the Height class, height1 andheight2.
You want to be able to add the two objects by using the +
operator. You can do this by overloading the + operator.
Method Overriding
Object-oriented programming enables a child class to
provide a specific implementation of a method that is
already defined in its parent classes. This is known as
method overriding. To override a method present in the
Updated Student Class parent class, the child class method should have the same
Method overloading allows you to use the same name for name, same parameters, and same return type as the
two or more methods. Each of these methods must use a method in the parent class.
different method signature. The signature of a method is Consider an example of the Shape class. This class has a
defined by: behavior called Draw. However, when you tell somebody
q The number of parameters. Consider the to draw a shape, the first question they ask is likely to be,
following methods: “What shape?” Simply telling a person to draw a shape is
AddNumber(numeric Num1) too abstract. You must specify which shape you require.
AddNumber(numeric Num1, Num2)
To do this, you extend the Shape class to create three sub
In the preceding pseudocode segment, the two
classes: Circle, Rectangle, and Cone. The Shape
methods are different because their number of
class has a Draw method to specify that all shapes need to
parameters is different.
implement this behavior. However, the method cannot be
q The data types of parameters. Consider the
implemented in the Shape class because the
following methods:
Display(numeric Num1) implementation of the method for each shape will be
Display(Character Message) different. Therefore, all the sub classes of the Shape class
In the preceding pseudocode segment, the two will override the Draw method defined in the Shape
class and provide their own implementation of the method. Car1.steer()
When a method is overridden, the version of the method The preceding statement invokes the steer method defined
that will be executed depends on the object that is used to in the Car class. This linking of the method invocation to
call it. If an object of a parent class is used to call the the appropriate method happens at the time of compiling
method, then the version in the parent class will be the program. Therefore, the preceding scenario represents
executed and if an object of the sub class is used to call the an example of static polymorphism.
method, then the version in the child class will be Dynamic Polymorphism
executed. Again consider the same example of Vehicle and Car
Consider a scenario where you have two classes, Square classes, where the Car class is created by extending the
and Rectangle. The Square class is the super class of Vehicle class. The Vehicle class contains a virtual
the Rectangle class. The Square class has a method method named steer that is overridden in the Car class.
called Area, which calculates the area of a square. The Vehicle1 is an object of the Vehicle class and Car1
Rectangle class extends the Square class and is an object of the Car class. Consider the following
implements the Area method to calculate the area of a method:
rectangle. Here, if you use an object of the super class to MyMethod (Vehicle v)
access the Area method, the Area method of the {
Square class will be called, whereas if you use an object v.steer()
of the sub class to access the Area method, the Area }
method of the Rectangle class will be called. The preceding method accepts an object of the Vehicle
class as parameter, and invokes the steer method of the
object passed as parameter.
Now, consider the following statements:
q MyMethod (Vehicle1)
q MyMethod (Car1)
Both the preceding statements can be used to invoke the
MyMethod method. In any object-oriented program, an
object of the super class can store an object of the child
class. Therefore, in the MyMethod method, the object v
of the Vehicle class can accept a parameter that is an
object of the Car class.
This means that the statement, v.steer() can invoke
the steer method of either the Vehicle class or the
Car class, depending on the type of object that is passed
to the MyMethod method. At compile time, there is no
way to determine which of the two methods will be
invoked by this statement. The linking of the method
invocation to an appropriate method happens at runtime.
This is known as dynamic polymorphism.
Types of Polymorphism
Polymorphism is of two types:
q Static: In static polymorphism, the response to a
function invocation is decided at compile time.
q Dynamic: In dynamic polymorphism, the
response to a function invocation is decided at
run time.
Static Polymorphism
Consider the example of a Vehicle class that contains a
method, named steer. Suppose you create a class,
named Car, by extending the Vehicle class. Next, you
override the steer method in the Car class to provide a
specific implementation of the method. Further, consider
that Car1 is an object of the Car class. Consider the
following statement:
than one form.
q Some techniques to implement polymorphism in
an object-oriented program are:
xMethod overloading
xOperator overloading
xMethod overriding
q In static polymorphism, the response to a function
invocation is decided at compile time.
q In dynamic polymorphism, the response to a
function invocation is decided at run time.

Reference Reading
Exploring the Concept of
Encapsulation

Reference Reading: Books Reference Reading: URLs


Let’s Practice Matt Weisfeld, The Object- http://www.codeproject.com/
oriented Thought Process KB/architecture/OO.aspx

Exploring the Concept of Inheritance

Reference Reading: Books Reference Reading: URLs


Bertrand Meyer, Object- http://pj.freefaculty.org/
oriented Software Swarm/Beta/
Construction C# SwarmUserGuide/
swarm.user.user1.02-obj-
adv.sect1.html

Exploring the Concept of


Polymorphism

Reference Reading: Books Reference Reading: URLs


Matt Weisfeld, The Object- http://www.cplusplus.com/
oriented Thought Process doc/tutorial/polymorphism/

Summary http://msdn.microsoft.com/
en-us/library/ms173152
In this chapter, you learned that: (VS.80).aspx
q Encapsulation is the process of enclosing data and
methods within a logical package, called class.
q Inheritance is the process of deriving new classes
from existing classes.
q A class that inherits or derives attributes from
another class is called a derived class, and the
class from which it is derived is called the base
class.
q Inheritance avoids redundancy in code and
enables easy maintenance of code.
q Abstraction focuses on the essential features of an
object.
q Polymorphism enables an entity to exist in more
Chapter 3
Designing an Object-oriented Program
Proper identification and design of classes is very
important for providing an effective solution to a business
case. It helps in reducing the complexity of software
systems. Proper identification of relationships between
classes also plays a vital role in the successful
development of a software solution.
In this chapter, you will learn to design classes for an
object-oriented program. In addition, you will learn about
various types of relationships between classes.
Consider a scenario where you have to create an
Objectives application to calculate the area and perimeter of a circle.
In this chapter, you will learn to: To solve this problem, you can create a class named
q Design classes Circle. The Circle class can have an attribute named
q Identify relationships between classes radius and four methods named showRadius,
setRadius, calculateArea, and
calculatePerimeter. The setRadius method
Designing Classes assigns a value to the radius attribute. The
The primary objective of object-oriented programming is showRadius method displays the value of the radius
to design classes for the purpose of creating totally attribute. The calculateArea method is used to find
independent objects. As a rule, an object should be the area of the circle and calculatePerimeter
responsible for itself. This means that an object should be method is used to find the perimeter of the circle. The
able to answer all the important questions about itself. following pseudocode depicts the general structure of the
This independence helps to achieve code reuse. Circle class:
Classes and objects are the base of object-oriented class
programming. Proper identification of classes, their Circle //
attributes, behavior, and their interaction with other classes Class declaration
is important for reducing the complexity of the {
applications and making them reusable. private numeric radius //
Instance variable
//
The Anatomy of a Class declaration
public setRadius(numeric r) //
When you define a class, you need to define both the data Method declaration
that it contains and the code that operates on that data. The {
data or variables defined within a class are called instance radius = r
variables. This is because each instance of the class, also }
called object, maintains its own copy of these variables. public showRadius() //
Therefore, the instance variables for one object are Method declaration
separate from the instance variables for another object. {
display “Radius: ” + radius //
Method body
}
public numeric calculatePerimeter() //
Method declaration
{
numeric Perimeter //
Method body
Perimeter = 2* 3.14* radius case-sensitive. The method name cannot be the
return (Perimeter) same as a variable name or any other item
} declared in the class.
public numeric calculateArea q Parameter list: Consists of a list of
() //Method declaration parameters separated by commas. Parameters are
{ used to pass and receive data to/from a method.
numeric The parameter list is written between parentheses
Area //Method after the method name. The parentheses are
body included even if there are no parameters.
Area=3.14 * (radius * radius) q Method body: This contains the set of
return (Area) instructions that perform a specific task.
} In the pseudocode for the Circle class, the Circle
} class has four methods, setRadius, showRadius,
Let us consider the various components of the preceding calculatePerimeter, and calculateArea. All
pseudocode one by one. these methods have public access.
Class Declaration The setRadius method takes a numeric parameter
A class is declared by using the class keyword. The and assigns the value of this parameter to the attribute,
general syntax for declaring a class is: radius. This method does not return any value.
class <class name> The showRadius method does not take any parameter
In the pseudocode for the Circle class, the name of the and does not return any value. It simply displays a
class is Circle. All the attributes and methods contained message indicating the value of the attribute, radius.
within the class are included in curly braces following the The calculatePerimeter method does not take any
name of the class. parameter and returns a numeric value. In the body of
Instance Variable Declaration the calculatePerimeter method, a new variable,
In a class, the instance variables or attributes are declared Perimeter of numeric type is declared. The perimeter
with their data type. The general syntax for declaring an of the circle is calculated and its value is assigned to the
attribute is: variable, Perimeter. This value is then returned to the
Access_specifier Datatype statement that called the method by using the return
attribute_name statement.
In the pseudocode for the Circle class, the Circle
class contains an attribute named radius of numeric
The variable, Perimeter is accessible only inside
data type with private access. the calculatePerimeter method. Therefore, the
Method Declaration and Body variable is said to have method scope.
The code that operates on the variables is written inside Similar to the calculatePerimeter method, the
methods. A method consists of two parts, method calculateArea method does not take any parameter
declaration and method body. and returns a numeric value. In the body of the second
The following syntax can be used to define a method: method, a new variable, Area of the numeric type is
<Access specifier> <Return type> declared. The area of the circle is calculated and its value
<Method name>(Parameter list) is assigned to the variable, Area. This value is then
{
returned to the statement that called the method by using
<Method body>
the return statement.
}
In the preceding syntax, the first line depicts the method
declaration and the contents within the curly braces depict
the method body. According to the preceding syntax, the
various elements of a method are:
q Access specifier: Determines the extent to
which a variable or method can be accessed from
another class.
q Return type: Specifies the data type of the
value returned by a method. Some methods do
not return any value.
q Method name: Is a unique identifier and is
public setRadius(numeric
r) //Method to set radius
{
radius = r
}
public showRadius
() //Method to show
radius
{
display “Radius: ” + radius
}
public numeric calculatePerimeter
() //Method to calculate

//perimeter
{
numeric Perimeter
Perimeter = 2* 3.14* radius
return (Perimeter)
Instantiating Objects }
In OOP, instantiation is the process of creating an instance public numeric calculateArea
or object of a class, giving it a name, and allocating it () //Method to calculate //area
some memory location. For example, to create an instance {
of the Circle class, you can use the following numeric Area
pseudocode segment: Area=3.14 * (radius * radius)
Circle c1 return (Area)
In object-oriented languages, when you instantiate a class, }
special methods called constructors are automatically }
called. Constructors are methods that have the same name Classes can also have parameterized constructors. You can
as the class and have no return type. Constructors are used pass some parameter values to such constructors. These
to construct an object of a class. parameter values are usually assigned to the attributes of
For example, you can create a constructor for the Circle the class before creating an object of the class. The general
syntax for declaring a parameterized constructor is:
class, as shown in the following pseudocode:
ClassName (datatype parameter1,
public Circle()
datatype parameter2..)
{
{
//code to construct the object
// code to construct the object
}
}
A constructor initializes the memory allocated to an
For example, you can create a constructor for the Circle
object. The code within the constructor should assign
initial values to the member variables required for class that takes a numeric parameter. The value of this
constructing an object. For example, if you need to create parameter can be used to initialize the radius attribute,
an object of class Circle with an attribute radius, you as shown in the following pseudocode segment:
can assign a value to radius in the constructor, as shown public Circle(numeric r)
in the following pseudocode segment: {
class Circle radius=r
{ }
private numeric You can use this constructor to create an instance of the
radius //Instance Circle class, as shown in the following pseudocode
variable segment:
public Circle Circle c1(4)
() //Constructor Similar to methods, constructors can also be overloaded.
{ You can define two or more constructors in the same class
radius=5 / with different parameter declarations, as shown in the
/Initializing the //attribute following pseudocode segment:
} class Circle
{
private numeric
radius //Instance
variable
public Circle
() //
Constructor
{
radius=5
//Initializing the attribute
}
public Circle(numeric
r) //Constructor
with parameter
{
radius=r
}
public setRadius(numeric
r) //Method to set
radius Accessing the Members of a Class
{ Once you have created an instance of the Circle class,
radius = r you can access (or call) the methods of the Circle class
} by using the following statements:
public showRadius c1.setRadius(10)
() //Method to c1.showRadius()
show radius numeric A = c1.calculateArea()
{ numeric P = c1.calculatePerimeter()
display “Radius: ” + radius
The first statement calls the setRadius method of the
}
object, c1 and passes the value, 10 as a parameter. This
public numeric calculatePerimeter
() //Method to calculate value is used by the method to initialize the radius
attribute of the c1 object.
//perimeter The second statement calls the showRadius method of
{ the object, c1.
numeric Perimeter The third and the fourth statements call the
Perimeter = 2* 3.14* radius calculateArea and calculatePerimeter
return (Perimeter) methods of the Circle class and assign the return values
} of these methods to the variables A and P, respectively.
public numeric calculateArea
() //Method to calculate
area The Circle class contains only one attribute. The
{ scope of this attribute is private. Therefore, the attribute is
numeric Area not accessible outside the class. However, any public
Area=3.14 * (radius * radius) attribute in a class can be accessed by using the following
return (Area) syntax:
}
} <objectName>.<attributeName>
You can create an instance of the Circle class by using
any of the following statements:
q Circle c1
q Circle c1(10)
Depending on the statement used for creating an instance
of the class, the appropriate constructor is invoked.
Identifying Classes Determining the Responsibilities of
Before developing an object-oriented application, it is Each Class
important to analyze the given business scenario to Once you have identified the classes for a given scenario,
identify various classes that are required for the working you need to determine the responsibilities of each class.
of the application. At times, this can be very challenging. For example, in the preceding scenario, the player has the
Poorly chosen classes can complicate the structure of an responsibility of moving left, moving right, jumping,
application, reduce reusability of code, and hinder climbing, hiding, and collecting coins. The dragon has the
maintenance. responsibility of moving left, moving right, following the
In order to identify classes, read through your business player, and killing the player by breathing out fire.
case listing the nouns that you come across. This list forms Once you have identified the responsibilities of each class,
the set of potential classes in your application. Do not analyze whether a class is doing too many things. In case a
expect to get all the classes right the first time. You may class has too many responsibilities, you must split it into
need to add, remove, and change classes throughout the multiple classes. A single class doing too many things is
design process. difficult to understand, modify, and reuse. On the other
Consider a scenario of a video game where you have a hand, creating too many classes result in increase in
player who has to collect 100 coins to win the game within complexity and difficulty in maintenance. Therefore, you
a given frame of time, and a dragon who has to kill the need to strike an appropriate balance between the number
player. Here, you can identify three nouns, player, dragon, of classes and the number of responsibilities of each class.
and coins. However, on further analysis, you will find that
only player and dragon need to be modeled as classes.
Coins can be represented as an attribute of the Player
class.
such as xCoordinate and yCoordinate to track the
position of the dragon.
Determining the Interactions Between The responsibilities of the classes identified in the
Classes preceding example depict the behavior (or methods) of
these classes. For example, the Player class can have
Classes do not exist in isolation. The responsibilities of the methods, such as moveLeft, moveRight, jump,
classes are interrelated. They interact with each other climb, hide, and collectCoins. Similarly, the
through objects. Dragon class can have methods, such as moveLeft,
In the preceding scenario, both the classes Player and moveRight, followPlayer, killPlayer, and
Dragon interact with each other. When the dragon attacks breatheOutFire.
the player, the player gets a message and reacts
accordingly. Also, the dragon reacts according to the
player’s behavior. For example, when the player moves,
the dragon tries to follow the player and get as close to the
player as possible.
Classes need to be designed in such a way that the
dependency between the classes is minimal. In other
words, the classes should be able to interact with each
other without knowing the implementation details of other
classes. When the dependency between classes is very
low, the classes are said to be loosely coupled. However,
when the dependency between classes is very high, the
classes are said to be tightly coupled.

Identifying the Scope of the Class


Members
The scope of a class member is the portion of the
application where it can be accessed. In order to maintain
the privacy of the members, the scope of the class
members should be limited.
Let us consider the preceding scenario. The dragon needs
to follow the motion of the player by moving left or right.
The followPlayer method of the Dragon class will
call the moveLeft or moveRight methods depending
on the position of the player. Here, the followPlayer
Identifying Attributes and Behavior method of the Dragon class should be accessible to the
users but the moveLeft and moveRight methods
Once you have identified the responsibilities of each class should not be accessible to the user directly. Therefore, the
and the interaction between classes, you can identify the scope of the followPlayer method should be public
attributes and behavior of each class. and the scope of the moveLeft and moveRight
Attributes define the characteristics of the class. They methods should be private.
store all the information about the class. For example, in While defining the scope of a class member, you need to
the preceding scenario, to track the movement of the take care to expose the minimal possible interface to the
player, the Player class can have attributes such as user. This means access should be provided only to the
xCoordinate and yCoordinate. Similarly, to track required members of the class. The accessible members of
the number of coins collected by the player, the Player the class form the interface of the class. The
class can have an attribute named coinsCollected. implementation of the functionality provided by the
On the same lines, the Dragon class can have attributes interface should be hidden from the user.
called composition. Composition relationship is also
called the “has-a” relationship. For example, a class
named Car has an Engine. Therefore, a composition
relationship exists between the objects of the Car and the
Engine classes.
The following figure shows the composition relationship
between a car and an engine.

Let’s Practice

Composition Relationship
Let us consider an example of the Passenger class.
Each passenger of a train has a ticket. The attributes of a
passenger are name, age, gender,
mealPreference, and ticket. Now, the Ticket
can also be considered as a separate class with attributes
such as trainID, coachNumber, seatNumber,
pnrNumber, and fare. Therefore, the Passenger
class consists of the Ticket class.

Identifying Relationships Between


Classes
There are various relationships between objects of
different classes in an object-oriented environment, such
as:
q Composition relationship
q Generalization relationship
q Utilization relationship
q Instantiation relationship

Composition Relationship
Generalization Relationship
OOP allows you to form an object, which includes another
object as its part. This mechanism of forming an object is Generalization or inheritance relationship is also called
the “is-a” relationship. Specialized classes are derived
from generalized classes. It is a relationship between super
classes and their sub classes. The sub class is a special
form of the super class. For example, dog is a mammal, so
Dog is a sub class of the super class, Mammal. The
generalization hierarchy of the Mammal class is shown in
the following figure.

Utilization Relationship
Generalization Hierarchy of the Mammal Class OOP allows a class to make use of another class. This kind
In OOP, generalization means that a class may inherit a set of relationship is called utilization. For example, BMW is
of attributes and behavior from another class. Consider the an object of the Car class, and Patrick is an instance of
generalization hierarchy of the Automobile class, as Driver class. Patrick drives a BMW. Another driver,
shown in the following figure. James, drives a bus. Therefore, both the Car and Bus
classes use the Driver class. This type of relationship
between a driver and a bus or a driver and a car is known
as the utilization relationship.
The following figure shows the utilization relationship
between a car and a driver; and a bus and a driver.

Hierarchy of the Automobile Class


In the preceding figure, the Car and Bus classes inherit
the characteristics of the Automobile class. The
Automobile class is a super class while Bus and Car
classes are its sub classes.
The super class is normally a generalized (common) class.
Generalization means that multiple classes can inherit
certain attributes from the same super class. While
generalizing, the structure and behavior that is common to
different classes are combined to form a common super Utilization Relationship
class. The super class represents generalization, and the Similarly, a student writes with a pencil while a painter
sub class represents specialization where attributes and draws with a pencil. Both the student and the painter use
methods from the super class are added, modified, or the pencil class. The relationship between the student and
hidden in the sub classes. the pencil, or the painter and the pencil is the utilization
relationship.
q Classes have both data and methods.
q The data or variables defined within a class are
called instance variables.
q All the objects of a class share the same copy of
methods.
q On instantiation of a class, special methods called
constructors are automatically called.
q Identification of classes is important. Poorly
chosen classes can complicate the structure of an
application, reduce reusability of code, and hinder
maintenance.
q Classes do not exist in isolation. They interact
with each other through objects.
q Attributes define the characteristics of the class.
They store all the information about the class.
q Methods define the responsibilities of the classes.
q The various types of relationships shared by
objects and classes are:
Instantiation Relationship xComposition relationship
xGeneralization relationship
An instantiation relationship, as the name suggests, is a xUtilization relationship
relationship between a class and an instance of that class. xInstantiation relationship
Some examples of instantiation relationships are:
q A BMW is a car.
q A chair is a type of furniture. Reference Reading
q ‘Gone with the Wind’ is a book.
q Jenifer is a student. Designing Classes

Reference Reading: Books Reference Reading: URLs


Let’s Practice Bertrand Meyer, Object- http://bertrandmeyer.com/
Match the given examples with the type of inheritance Oriented Software category/design-by-
relationships that exist between them: Construction C# contract/
Relationships:
1. Composition
2. Utilization
Options:
Mobile has a Bluetooth
Pilot uses plane
Painter uses brush
Computer has a keyboard
Photographer uses camera
Room has an AC
Answer:
1.Composition: Computer has a keyboard
Mobile has a Bluetooth
Room has an AC
2.Utilization: Pilot uses plane
Photographer uses camera
Painter uses brush

Summary
In this chapter, you learned that:
V
Variable
Is a location in the memory that has a name and contains a
Glossary value.
A
Abstraction
Is a feature of object orientation that involves representing
only the relevant information.
Access Specifier
Defines the scope of a class member.
Attribute
Is a variable declared inside a class.
C
Class
Is a declaration, a template, or a blueprint that can be used
to define objects.
Constructor
Is a special type of method that is invoked when you
create a new instance of a class.
E
Encapsulation
Is a feature of object orientation that involves packaging
one or more components together.
F
Function
Is a set of statements that performs a specific task in
response to a message.
G
Generalization
Is the process of creating super classes that are a
generalized form of the corresponding sub classes. There
is an “is a” relationship between the sub class and the
super class.
I
Inheritance
Is a process of creating a new class by adding some
features to an existing class.
Instantiation
Is a relationship between a class and an instance of that
class.
Interface
Is the fundamental means to interact with a class.
M
Method
Is a set of one or more program statements, which can be
executed by referring to the method name.
O
Object
Is a combination of data and behavior.
P
Polymorphism
Is the ability of an entity to exist in different forms.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy