OOPS
OOPS
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.
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
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.
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.
Reference Reading
Exploring the Concept of
Encapsulation
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.
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.
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.
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.