MT
MT
Programming
Dr. Bharat Singh
PhD, CSE
History
History
• Object-oriented programming (OOP) is a programming paradigm that
has revolutionized the way software is developed.
• OOP traces its roots back to the 1960s when computer scientists
began to explore new ways of organizing and structuring code.
• The concept of objects, which encapsulate data and behavior, was
introduced to improve software development processes.
• One of the earliest programming languages that embraced OOP
principles was Simula, developed in the 1960s by Ole-Johan Dahl and
Kristen Nygaard. Simula introduced the concept of classes and
objects, laying the foundation for modern OOP languages.
• OOP is a fundamental concept in many programming languages,
including Python, Ruby, and C#.
History
Software Evolution 5
• These layers are built up one by one over the last five decades.
• However, the each layer is improvement over the previous one, BUT each of the
layers continues to be functional NOT like tree where only the uppermost layer
is functional.
7
• To build today’s complex software system, it is just not enough to put together a
sequence of programming statements and set of procedures and modules.
• However, when the program grew larger even structured programming approach
failed to show desired results in terms of bug-free results, easy-to-maintain and
reusable programs.
10
• It is a new way to organize and develop programs and has nothing to do with
any particular language.
What is programming?
11
Programming
Programming (Conti..)
• Procedural Languages
• C, Pascal, Basic, Fortran
• Facilities to
• Pass arguments to functions
• Return values from functions
Programming (Conti..)
• Some characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing thins (Algorithms)
• Large programs are divided into smaller programs know as functions.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach of program design.
• Main Drawbacks:
• Very little attention given to the data that are being used by various functions. In a large program it is
difficult to identify what data is used by which function.
• Global data are more vulnerable to an inadvertent change by a function.
• It does not model real world problems very well. This is because functions are action-oriented and do not
really correspond to the elements of the problem.
Procedural Programming
• Advantages
• General-purpose programming
• Code reusability
• Portable source code
• It is easy to trace the flow of the program
• Disadvantages
• Data protection
• Not suitable for real-world objects
Object Oriented Programming
• Object-oriented programming can be defined as a programming
model which is based upon the concept of objects.
• An object has two characteristics:-
• attributes
• behaviors
• For example, an object could represent an employee with attributes
such as name, title, experience, etc., with behaviors like working, on-
leave, underperformed.
• Objects contain data in the form of attributes/properties and code in
the form of methods/behaviours.
Object Oriented Programming
• In object-oriented programming, computer programs are designed
using the concept of objects that interact with the real world.
• Object-oriented programming languages are various but the most
popular ones are class-based, meaning that objects are instances of
classes, which also determine their types.
• Many of the most widely used programming languages (such as C++,
Java, and Python)
• Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart,
Swift, Scala.
Object Oriented Programming
• Advantages:-
class animal:
• It can relate to real-world entities. species = "bird"
def__init__(self, name, age):
• Code Reusability self.name = name
• Data hiding self.age = age
Paradigm
11/28/2024
Object-Oriented Concept 28
11/28/2024
Object-Oriented Concept (Conti..) 29
• Major motivating factor in the invention of Object-oriented approach is to remove some flaws encountered in the
procedural programming languages.
• OOP treats data as a critical element in the program development and does not allow it to flow freely around the
system.
• It ties data closely to the functions which operate on it, and protect it from accidental modification from outside
functions.
• OOP decompose the problem in smaller entities called as objects, and build data and functions around it.
• It provides the basic concepts of:
• Objects
• Classes
• Data Abstraction
• Data Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Objects 30
11/28/2024
Objects 31
11/28/2024
32
OO Perspective
In C++, rather than writing a procedure, we define a class that encapsulates the knowledge
necessary to answer the question - here, what is the area of the rectangle.
11/28/2024
Example Object Oriented Code
33
Object-oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area of both
data and functions that can be used as templates for creating copies of such modules on demand
1.2 Object Oriented Paradigm
• Features:
1. Emphasis on data than procedure
2. Programs are divided into what is known as objects
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together in data
structure.
5. Data is hidden and cannot be access by external functions.
6. Objects may communicate with each other through methods
7. New data and methods can be added whenever necessary.
8. Follows bottom up approach in program design.
• Object-oriented programming is an approach that provides a way of
modularizing programs by creating partitioned memory area for both
data and functions that can be used as a templates for creating copies
of such modules on demand.
1.3 Basic Concepts of Object Oriented
Programming
• Object and Classes
• Data abstraction and Encapsulation
• Inheritance
• Polymorphism
• Compile Time and Runtime Mechanisms
• Dynamic binding
• Message Communication
1.3 Basic Concepts of Object-Oriented
Programming
Object and Classes
• Basic runtime entities in an object-oriented system.
• Can be any item that program has to handle or can also be user
defined data types such as vectors or lists.
• In OOP, programming is all about objects and nature of
communication between them.
• Objects chosen must be close to real-world objects.
• When a program is executed, the objects interact by sending
messages to one another.
1.3 Basic Concepts of Object-Oriented
Programming
Objects and Classes
• Each object contains the data and code to manipulate data.
• Objects can interact without knowing the details of each other’s data
or code.
Representation of an object in
object-oriented analysis and design
1.3 Basic Concepts of Object-Oriented
Programming
Objects and Classes
• Data and code of an object can be made user-defined data type using
the concept of a class.
• Class can be thought of as a ‘data type’ and an object as a variable of
that data type.
• Once a class has been defined we can create any number of objects
for that class.
• Each object is associated with the data type class with which they are
created.
• Basically a class is a collection of objects of similar type.
Classes
• Inheritance means one class of objects inherits the data and behaviors from another class.
Inheritance maintains the hierarchical classification in which a class inherits from its parents.
•Inheritance provides the important feature of OOP that is reusability. That means we can
include additional characteristics to an existing class without modification. This is possible
deriving a new class from existing one.
• Inheritance is a relationship between classes where one class is the parent class of another
(derived) class.
•The derived class holds the properties and behaviour of base class in addition to the
properties and behaviour of derived class.
• Inheritance allows for the creation of new classes based on existing
classes.
• This promotes code reusability by allowing a new class to inherit the
properties and behaviors of an existing class.
• This reduces code duplication and makes it easier to manage and
maintain large codebases.
1.3 Basic Concepts of Object-Oriented
Programming
Polymorphism
1.3 Basic Concepts of Object-Oriented
Programming
• Polymorphism means the ability to take more than one form.
• A single function name can be used to handle different number and
different types of arguments.
• Allows objects having different internal structures to share the same
external interface.
• General class of operations may be accessed in the same manner
even though specific actions associated with each operation may
differ.
• Extensively used in implementing inheritance.
Polymorphism
Packages
•
Classes and Interfaces
Methods
Benefits of OOP in Modern Development
• OOP provides several benefits in modern software development:
• Code reusability
• Maintainability
• Scalability
• Flexibility
• Modularity
Benefits of OOP in Modern Development
• OOP provides several benefits in modern software development:
• Code reusability: OOP allows for the creation of reusable code
components, which can be used in different parts of an application or
even in different applications altogether. This reduces code
duplication and makes it easier to maintain and update code.
• The object contains both data and code: Data in the form of
properties (often known as attributes), and code, in the form
of methods (actions object can perform).
What is Object Oriented Programming ?
• class class_name:
• '''This is a docstring. I have created a new class'''
• <statement 1>
• <statement 2>
class ClassName:
• .
• . initializer
• <statement N> methods
Example: Define a class in Python
• In this example, we are creating a Person Class with name, sex, and
profession instance variables.
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
# A sample method
def fun(self):
print("I am a", self.attr1)
print("I am a", self.attr2)
•<object-name> = <class-name>(<arguments>)
•for example
• jessa = Person('Jessa', 'Female', 'Software Engineer')
# Python program to demonstrate instantiating a class
class Person:
# A simple class attribute
attr1 = "smart boy"
attr2 = "smart girl"
# A sample method
def fun(self):
print("I am a", self.attr1)
print("I am a", self.attr2)
def greet(self):
print("hope you are doing well")
# Driver code
# Object instantiation
# instance Method
def show(self):
print('Hello, my name is', self.name)
# call methods
jessa.show()
jessa.work()
Constructor
• A constructor is a special method used to create and initialize an object of a
class.
• Constructors are used to initializing the object’s state.
• This method is defined in the class.
• The constructor is executed automatically at the time of object creation.
• The primary use of a constructor is to declare and initialize data member/ instance
variables of a class. The constructor contains a collection of statements (i.e., instructions)
that executes at the time of object creation to initialize the attributes of an object.
• For example, when we execute obj = ClassName(), Python gets to know that
obj is an object of ClassName and calls the constructor of that class to create
an object.
• On the other hand, a destructor is used to destroy the object.
Constructor
• In Python, Object creation is divided into two parts in Object Creation
and Object initialization
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Constructor
• Note:
• For every object, the constructor will be executed only once. For
example, if we create four objects, the constructor is called four
times.
• In Python, every class has a constructor, but it’s not required to define
it explicitly. Defining constructors in class is optional.
• Python will provide a default constructor if no constructor is defined.
Types of Constructors
• In Python, we have the following
three types of constructors.
1. Default Constructor
2. Non-parametrized constructor
3. Parameterized constructor
Default Constructor
• Python will provide a default constructor if no
constructor is defined. Python adds a default
constructor when we do not include the constructor in
the class or forget to declare it. It does not perform
any task but initializes the objects. It is an empty class Employee:
constructor without a body.
def display(self):
• If you do not implement any constructor in your class print('Inside Display')
or forget to declare it, the Python inserts a default
constructor into your code on your behalf. This
constructor is known as the default constructor. emp = Employee()
emp.display()
• It does not perform any task but initializes the objects.
It is an empty constructor without a body.
• If you implement your constructor, then the default
constructor will not be added.
Non-Parametrized Constructor
class Company:
• A constructor without any # no-argument constructor
arguments is called a non- def __init__(self):
parameterized constructor. This self.name = "PYnative"
type of constructor is used to self.address = "ABC Street"
initialize each object with default
# a method for printing data members
values. def show(self):
print('Name:', self.name, 'Address:', self.address)
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
c2=Circle(5)
print("the area of the circle of radius ",c2.radius, " is"
,c2.getArea())
c3=Circle(25)
c4=Circle(125)
Write a Python program to create a calculator
class. Include methods for basic arithmetic
operations. # Define a class called Calculator to
perform basic arithmetic operations
class Calculator:
# Define a method for addition that takes
two arguments and returns their sum
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y !=0:
return x / y
else:
return("Cannot divide by zero.")
calculator = Calculator()
result = calculator.add(7,5)
print("the sum of 7 + 5 =", result)
Example class Car():
# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color
def show(self):
print("Model is", self.model )
print("color is", self.color )
instance_name.attribute_name.
• A class variable is accessed or modified using the class name
class Student:
# class variables
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)
def show(self):
print("Fruit is", self.name, "and Color is", self.color)
# delete object
del emp
# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('Object initialized')
def show(self):
print('Hello, my name is', self.name)
# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')
# create object
s1 = Student('Emma')
s1.show()
# delete object
del s1
Important Points to Remember about
Destructor
• The __del__ method is called for any class Vehicle:
object when the reference count for def __init__(self, speed):
that object becomes zero. self.speed = speed;
• The reference count for that object def __del__(self):
becomes zero when the application print('Release resources')
ends, or we delete all references
manually using the del keyword. # creating an object
car = Vehicle(350);
• The destructor will not invoke when
we delete object reference. It will # to delete the object explicitly
del car
only invoke when all references to
the objects get deleted.
The self Parameter Python
• The class contains instance variables and methods. class GFG:
• Whenever we define instance methods for a class, def __init__(self, name, company):
we use self as the first parameter, but it is not used self.name = name
when the method is called. self.company = company
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
# Uncommenting print(obj1.c) will raise an AttributeError
# Uncommenting obj2 = Derived() will also raise an
AttributeError as private member of base class is called inside
derived class
Private Member
• We can access private members from outside of a class using the
following two approaches
• Create public method to access private members
• Use name mangling
Public method to access private members
class Employee:
# constructor
• Access Private member outside def __init__(self, name, salary):
of a class using an instance # public data member
self.name = name
method # private member
self.__salary = salary
# getter method
def get_age(self):
return self.__age
# setter method
def set_age(self, age):
self.__age = age
# Parent class 2
• one child class can inherit from class Company:
multiple parent classes. So here def company_info(self, company_name, location):
print('Inside Company class')
is one child class and multiple print('Name:', company_name, 'location:', location)
parent classes.
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee info(12000, 'Machine Learning')
Multilevel inheritance
• a class inherits from a child class
or derived class.
• Suppose three classes A, B, C. A
is the superclass, B is the child
class of A, C is the child class of
B.
• chain of classes is called
multilevel inheritance.
# Base class
Multilevel inheritance
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
class Car(Vehicle):
• Example def car_info(self, name):
print("Car name is:", name)
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
class Vehicle:
def vehicle_info(self):
Hybrid Inheritance print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
• When inheritance is consists of print("Inside Car class")
multiple types or a combination class Truck(Vehicle):
of different inheritance is called def truck_info(self):
hybrid inheritance. print("Inside Truck class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()