Object
Oriented Programming
KEY-POINT
• Uses
the bottom-up approach
• Data
takes precedence over the process
• Promotes
Reusability
• Exploits
Commonality
• Reduces
Complexity
• Facilitates
maintenance
Why Object oriented
Programming ?
• Object oriented
technology offers a new model where data and processes are integrated.
• Data and processes
are packaged together to form an object.
• The object contains
all the information and the data which is required to provide the functionality
for which it
is designed.
Advantages of Object
Oriented Programming:
• One of the principal
advantages of object-oriented programming techniques over Structured
Programming
techniques is that it
allows programmers to create modules that do not need to be changed when a new
type of
object is added. A
programmer can simply create a new object that inherits many of its features
from the
existing objects.
• The user dictates
the flow of control to the application, thereby being very user-friendly and
providing flexibility.
• It’s considered to
be more suitable for representing real world objects than Structured
programming.
Features
of Object Oriented Technology
• Abstraction
• Class
• Object
• Encapsulation
• Access Specifiers
• Data Hiding
• Inheritance
• Polymorphism
• Abstraction -> It
denotes the essential characteristics of an object that distinguish it from all
other
kind of objects and thus provide
crisply defined conceptual boundaries, relative to the perspective of
the viewer. It focuses on
observable behavior of an object.
• Encapsulation ->
Focuses upon the implementation that gives rise to the observable behavior.
• Access Specifiers
• Data Hiding
• Inheritance -> Opens
the possibility of extending and adapting object description and
implementation without changing
their source code.
• Polymorphism
• Static and Dynamic Polymorphism
What
is a Class ?
• Class -> It is a set
of objects that share a common structure and a common
behavior.
• Data Member
• Member Methods -> denotes the
service that a class offers to its client.
• A Class
• is a software
template that defines the methods and variables to be
included in a
particular kind of Object.
• Is a blue print used
to create objects. As it is a blue print, at run
time it will not
occupy any memory.
• Examples :
• Animal, Human being,
Automobiles.
• Classes increase the efficiency
and power of the object by:
Classifying objects
Relating objects to one another
Providing a mechanism to define
and manage objects
Class Contains,
• Member Data
• Variables defined
inside a class
• Normally Member data
are hidden
• Member Methods
• Functions defined
inside the class
• Member methods are
public in nature and accessible from outside
the class
Declaring Classes
We declare classes using the following syntax:-
class < Class Name >
{
data members…
member functions…
}
Here class is a keyword.
We declare classes using the following syntax:-
class < Class Name >
{
data members…
member functions…
}
Here class is a keyword.
Example
Class:-
CODE :
class
Student
{
// Data Members
public string Name;
public int Age;
// Member Function
public void Display()
{
Console.WriteLine("Name {0}\n Age {1}", Name, Age);
}
}
{
// Data Members
public string Name;
public int Age;
// Member Function
public void Display()
{
Console.WriteLine("Name {0}\n Age {1}", Name, Age);
}
}
What
is an Object ?
• Object -> Object is an
instances of a class. Thus an object is an entity that has
attributes and provide certain
operations that are defined for the particular object.
• An object
• Is an unique,
identifiable, self-contained entity that possesses
operations and
contains attributes
• Possesses all the
know-how and information it needs to perform
the services for which
it was designed
• which receives and
sends messages
Creating objects is similar to
declaring variables and can be done using the syntax:-
<Class Name> <Object Name>= new <Class Name>;
Example:
<Class Name> <Object Name>= new <Class Name>;
Example:
class
Student
{
// Data Members
public string Name;
public int Age;
// Member Function
public void Display()
{
Console.WriteLine("Name {0}\n Age {1}", Name, Age);
}
}
{
// Data Members
public string Name;
public int Age;
// Member Function
public void Display()
{
Console.WriteLine("Name {0}\n Age {1}", Name, Age);
}
}
Class
Name : Student
Student S1 = new Student();
Using the Objects
We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();
Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;
We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();
Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;
CODE :
namespace CSTutorials
{
class Student
{
// Data Members
public string Name;
public int Age;
// Member Function
public void Display()
{
Console.WriteLine("Name {0}\n Age {1}", Name, Age);
}
}
class Program
{
static void Main(string[] args)
{
Student S1; // Declaration
S1 = new Student(); // Instantiation
Student S2 = new Student(); // Single line Declaration & Instantiation
// Assigning value to member variables
S1.Name = "Michael";
S1.Age = 37;
S1.Name = "Kimi";
S2.Age = 25;
// Invoking member function
S1.Display();
S2.Display();
Console.ReadLine();
}
}
}
Abstraction
• Focuses
upon the essential elements and characteristics of
some
object, relative to the perspective of the viewer
• In
Object Oriented Programming, we try to handle
complexity
by using the concepts of class and object
Example:
• Take an entity as BOOK.
Let us try to find out the different characteristics of the same
entity from the perspective of the
viewer.
• Let us take 2 cases where the
same entity BOOK can be viewed differently:
• Library System
• In this case we will be focusing
on Access Number, Book Name, Author
Name
• Shopkeeper
• In this case we will be focusing
on Item Number, Item Name, Price,
Quantity On Hand.
Encapsulation:
Data Encapsulation combines data
and functions into a single unit called Class. When using Data Encapsulation,
data is not accessed directly; it is only accessible through the functions
present inside the class. Data Encapsulation enables the important concept of
data hiding possible.
Encapsulation & Abstraction
Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.
Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).
Consider the example from the programmer’s perspective who wants to allow the user to add items to a list. The user only needs to click a button to add an item (Abstraction). The mechanism of how the item is added to the list is not essential for him (Encapsulation).
Below is a graphical representation of Encapsulation for the car class.

Implementing Encapsulation & Abstraction
Consider the countless advertisements being bombarded to viewers. The viewer does not listen to each one of them, rather only those he’s curious about. We use access specifiers to restrict the scope (visibility) of the class members.
Types of Access Specifiers
Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.
Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).
Consider the example from the programmer’s perspective who wants to allow the user to add items to a list. The user only needs to click a button to add an item (Abstraction). The mechanism of how the item is added to the list is not essential for him (Encapsulation).
Below is a graphical representation of Encapsulation for the car class.
Implementing Encapsulation & Abstraction
Consider the countless advertisements being bombarded to viewers. The viewer does not listen to each one of them, rather only those he’s curious about. We use access specifiers to restrict the scope (visibility) of the class members.
Types of Access Specifiers
- public - The members (Functions & Variables) declared as public can be accessed from anywhere.
- private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;
- protected - Protected members can be accessed only from the child classes.
- internal - Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.
Code:
class House
{
// Data Members
public string DrawingRoom;
private string Kitchen;
// Member Functions
private bool EnterDrawingRoom()
{
DrawingRoom = "The Drawing Room";
}
public bool EnterKitchen()
{
Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function
can modify it because the member function itself has access to all other members. */
}
}
class MainClass
{
public static void Main()
{
House TheBlackHouse = new House();
TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible
from outside the class */
TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible
from outside the class. */
TheBlackHouse.EnterDrawingRoom(); /* Error - Private Member Function is not accessible
// from outside the class. */
TheBlackHouse.EnterKitchen(); /* OK - Public Data Member is accessible from outside
the class. */
}
}
{
// Data Members
public string DrawingRoom;
private string Kitchen;
// Member Functions
private bool EnterDrawingRoom()
{
DrawingRoom = "The Drawing Room";
}
public bool EnterKitchen()
{
Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function
can modify it because the member function itself has access to all other members. */
}
}
class MainClass
{
public static void Main()
{
House TheBlackHouse = new House();
TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible
from outside the class */
TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible
from outside the class. */
TheBlackHouse.EnterDrawingRoom(); /* Error - Private Member Function is not accessible
// from outside the class. */
TheBlackHouse.EnterKitchen(); /* OK - Public Data Member is accessible from outside
the class. */
}
}
Inheritance
•
Ability to compose new abstraction from existing one
•
Implements the concept of Re-usability
•
Classes are arranged in a tree like structure called a
hierarchy
•
Base class:
• the
class providing the implementation
•
Derived class:
• the
class inheriting the implementation
• Inheritance also promotes reuse.
You don't have to start from scratch when you write a new
program. You can simply reuse an
existing repertoire of classes that have behaviors similar to what
you need in the new program.
• Base class is also called Super
Class and Derived class is called Child class.
• Derived class can also override
the inherited method
• By using the concept of
inheritance, it is possible to create a new class from an existing one and
add new features to it. Thus
inheritance provides a mechanism for class level reusability.
public class Base
{
int Var1;
int Var2;
}
public class Derived : Base
{
public void MyMethod()
{
Var1 = "Value";
Var2 = "Value";
}
}
public class Unrelated
{
public void MyMethod()
{
Base B = new Base();
B.Var1 = "Value";
{
int Var1;
int Var2;
}
public class Derived : Base
{
public void MyMethod()
{
Var1 = "Value";
Var2 = "Value";
}
}
public class Unrelated
{
public void MyMethod()
{
Base B = new Base();
B.Var1 = "Value";
B.Var2
= "Value";
}
}
}
}
class Animal
{
public Animal()
{
Console.WriteLine("Animal constructor");
}
public void Greet()
{
Console.WriteLine("Animal says Hello");
}
public void Talk()
{
Console.WriteLine("Animal talk");
}
public virtual void Sing()
{
Console.WriteLine("Animal song");
}
};
Now see how we derive another class from this base class.class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog constructor");
}
public new void Talk()
{
Console.WriteLine("Dog talk");
}
public override void Sing()
{
Console.WriteLine("Dog song");
}
};
code out.Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();
Animal a2 = new Dog();
a2.Talk();
a2.Sing();
a2.Greet();
//Output
Animal constructor
Animal talk
Animal song
Animal says Hello
//Output
Animal constructor
Dog constructor
Animal talk
Dog song
Animal says Hello
Inheritance
: Example
• “Shape”
is the root class
• “Polygon”
is a derived class
from
“Shape” class
• “Polygon”
is the super class for
“Triangle”,
• Generalization
and
Specialization
are associated
with
the concept of Inheritance
• In a class hierarchy, every
class has a superclass except for the class at the top of the hierarchy;
this class is called the root
class
• In our example, Shape is the
root of the hierarchy. From the other end, the classes that don’t have
any subclasses, like Rectangle and
Isosceles are called leaf classes.
Generalization
and Specialization
• Consider
the two classes in the
diagram
(Person and Student)
• “Student”
class inherits the
properties
from “Person” class
• “Person”
is a generalization of
“Student”
• “Student”
is a specialization of
“Person”
• Specialization is the
process as we go down the class hierarchy
• of maximizing the differences between
members of an entity by identifying their
distinguishing characteristics
• of defining subclasses that are
more refined than superclass – its specialized
• Generalization is the
process as we go up in the class hierarchy
• of minimizing the differences
between entities by identifying their common
characteristics
• of defining Superclass which
contains common characteristics of its subclasses – its
Generalized
Multiple
and Multilevel Inheritance
• Single
inheritance is having
common characteristics
with only
one superclass.
• Ex: Class
“Quadrilateral”
• Multiple
inheritance means that a
class has common
characteristics
with more than one
superclass
• Ex: Class “Square”
• Multilevel
inheritance talks about
level of inheritance
hierarchy.
• Ex: 4th Level
• Single inheritance, where
each class (except the root) has one and only one superclass.
• Multiple inheritance,
where a class inherits from more than one superclass.
• Multilevel inheritance, where
class hierarchy goes for more than one level. The level of
hierarchy in the example shown in
the slide above is 4.
Advantages
of Inheritance
• Software
reusability
• Design
and code sharing
• Software
components
• Rapid
prototyping
Polymorphism
• Is
the ability of different objects to respond in their own
unique
way to the same message
•
Implemented by overloading and overriding
•
Possible because of Encapsulation and Inheritance
•
Example of a class hierarchy where vehicles is the base
class
and there are some classes which are derived from
vehicles.
( Car, Plane, Bicycle)
•
Each of the classes need a functionality called “Stop”.
• Polymorphism allows us to send
identical messages to dissimilar but related objects and achieve
identical actions while letting
the software system to determine how to achieve the required action for
the given object.
• The sender of a message does not
need to know the receiver's class .
• It serves the purpose of
structuring systems around WHAT is to be done, and allows details about
HOW classes and methods are implemented to be
hidden.
• It allows a general class to
specify methods that will be common to all of its derivatives, while
allowing subclasses to define the
specific implementation of some or all of those methods.
• Explanation of the above Example
:
• All vehicles offered an
operation “stop”.
• Implementation of the “stop”
method will be different for different classes.
• At runtime user will invoke a
method “stop”.
• The effect is that upon
receiving the message the object knows to which class it belongs
to, and thus executes the “stop”
method for its own class.
• Message is the same called
“stop” but which method is going to get invoked depends upon which
type of class the object is
sending the message.
• Message is the same but the
execution might vary depending upon the derived class
implementation.
• Different Object
Oriented Languages use different
concepts of
implementing polymorphism
• Function Overloading
• Operator Overloading
• Function Overriding
•C++ supports all the
above features where as java does not support Operator Overloading.
Function/Method
Overloading
• Ability to define
two or more methods with the same
names and different
signatures
• Signature means
number of arguments, type of
arguments and sequence
of arguments
• Ex:
1. void disp(int ix);
2. void disp(int
ix,int iy);
3. void disp(int
x,char cy);
4. void disp(char
cx,int iy);
• Method
Overloading
• When a Class is
having more than one method with the same name but of different
signature.
• Function prototype 1
and 2 differ in number of arguments
• Function prototype 2
and 3 differ in type of arguments
• Function prototype 3
and 4 differ in sequence of arguments
• Definition Given
by IEEE:
• To assign an
operator, identifier or literal more than one meaning, depending upon the
data types associated
with it at any given time during program execution.
CODING:
using System;
namespace CalculateMax
{
class CalculateMax
{
public int Max(int number1, int number2)
{
if(number1 > number2)
{
return number1;
}
else
{
return number2;
}
}
public float Max(float number1, float number2)
{
if(number1>number2)
{
return number1;
}
else
{
return number2;
}
}
}
class MaxCalc
{
static int Main(string[] args)
{
CalculateMax calc = new CalculateMax();
Consol;e.WriteLine(("{0}",calc.Max(5.4F,8.6F));
//Both function calls differ
Console.WiteLine("{0}",calc.Max(19,21));
//Only in their parameters
Console.ReadLine();
return 0;
}
}
}
Operator Overloading
• Operator overloading
in the language gives a new meaning
for the operands of a
specific class
• Operator overloading
provides a way to define and use
operators such as +,
-, *, /, and [] for user defined types
such as classes
• Some of the OOP
languages support this
• It's common to define a meaning
for an existing operator for objects of a new class.
• We want to use the operators for
user defined data types (user defined class) also.
• C++ supports overloading of
operators where as java does not allow this.
Overriding
• Process of defining
the methods with the same name and
signature in derived
class which already exists in the
Base/Parent class
• Process of
re-defining the methods in the derived class
• Methods must have
argument lists with the identical type
and order as the
superclass
• Subclasses can alter or override
information inherited from parent classes for exceptional cases
• All mammals give birth to young
ones
• Some mammals lay eggs
• The ability of a subclass to
override a method in its superclass allows a class to inherit from a
superclass whose behavior is
"close enough" and then override methods as needed.
• When you override a method of a
superclass you should honor the intended behavior of the method.
Example in C++:
class animal
{
protected:
int speed;
char color[20];
public:
virtual void
init_speed()
{
}
virtual void init_color()
{
}
};
In the above example, both the
method( init_speed() and init_color() ) are overridden in the derived
classes called “Dog” and “Tiger”.
class dog:public
animal
{
public:
void init_speed()
{
speed=40;
cout<<"Speed
of a dog is "<<speed<<endl;
}
void init_color()
{
strcpy(color,"Black");
cout<<"Color
of a dog is "<<color<<endl;
}
};
In the above example,
both the method( init_speed() and init_color() ) are overridden in the derived
classes called “Dog”
and “Tiger”.
class tiger:public animal
{
public:
void init_speed()
{
speed=90;
cout<<"Speed
of a Tiger is "<<speed<<endl;
}
void init_color()
{
strcpy(color,"White");
cout<<"Color
of a Tiger is "<<color<<endl;
}
};
In the above example,
both the method( init_speed() and init_color() ) are overridden in the derived
classes called “Dog”
and “Tiger”.
Example to understand
Polymorphism:
using
System;
public class Customer
{
public virtual
void CustomerType()
{
Console.WriteLine("I am a customer");
}
}
public class CorporateCustomer
: Customer
{
public override
void CustomerType()
{
Console.WriteLine("I am a corporate customer");
}
}
public class PersonalCustomer
: Customer
{
public override
void CustomerType()
{
Console.WriteLine("I am a personal customer");
}
}
public class MainClass
{
public static
void Main()
{
Customer[] C = new Customer[3];
C[0] = new CorporateCustomer();
C[1] = new PersonalCustomer();
C[2] = new Customer();
foreach (Customer CustomerObject in
C)
{
CustomerObject.CustomerType();
}
}
}
Binding
• Process of
connecting a method call to a method body.
• Static
• Binding is performed
before the program runs – Compile time
• Dynamic
• Binding is performed
at the time of execution – Run time
• A binding is an
association between an operation and an entity.
• The process of binding can
happen either at compile time or at run time.
• Compile time binding is called
as Static Binding.
• Run time binding is called as Dynamic
Binding.
Static Binding
• Method calls are
bound to specific computer memory
locations where
methods are placed at compile time
• Leads to run-time
efficiency since the compiler can
optimize code before
executing it
• Function Overloading
implements static binding
• Object is going to
invoke which overloaded method is
decided at the time of
compilation by looking at the
signature
• Every time a function call is
executed, the system will jump to the location where the function code
is stored, and will execute the
code.
• This is called static binding
or early binding.
• Static binding is the default
behavior for all C++ functions and member functions.
• Overloaded functions are
implemented using static binding.
• As binding time gets earlier:
• efficiency goes up
• safety goes up
• flexibility goes down
Dynamic Binding
• The method called
depends upon the type of the object
and not the type of
the expression
• The type cannot
always be resolved at compile time
• Dynamic binding
resolves the method to be used at run-time
• Method overriding
implements the concept of dynamic
binding
• Offers the
advantages of flexibility and a high level of
problem abstraction
Dynamic Binding:
• Physical behavior is taken on
last possible instance - Runtime
Pros and Cons of Dynamic Binding
• Pros
• Good evolution: Can easily add a
new derived class with new method
implementations
• Easy to iterate over similar
types of objects
• Cons
• Performance: Run-time lookup
based on type
• Have to design base classes
carefully—Don’t want to break derived classes
• Harder to understand code—have
to study several classes