Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects,
which are instances of classes. OOP helps in designing modular, reusable, and maintainable code.
1. Concepts of OOP
1.1 Object
An object is a real-world entity that has state (data/attributes) and behavior (functions/methods).
Example: A car is an object. It has:
• State: Color, model, engine capacity, fuel type
• Behavior: Accelerate, brake, turn, honk
In programming, an object is created from a class.
1.2 Class
A class is a blueprint or template for creating objects. It defines the attributes (variables) and
methods (functions) that its objects will have.
Example: Think of a car manufacturing blueprint. It defines how a car should be built, but an
actual car is an object made from that blueprint.
Python Example:
class Car:
def __init__(self, brand, color): # Constructor
[Link] = brand # Attribute
[Link] = color # Attribute
def start(self): # Method
print(f"{[Link]} car has started.")
# Creating an object of class Car
car1 = Car("Toyota", "Red")
[Link]() # Output: Toyota car has started.
2. Four Main Principles of OOP
2.1 Encapsulation (Data Hiding)
Encapsulation means wrapping data and methods within a class and restricting direct access to
some details of the object.
Why?
• Protects data from unintended modification
• Provides control over the data
Example: In a bank account system, the balance should not be directly accessible or modified.
Instead, it should be accessed through methods.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def deposit(self, amount):
self.__balance += amount
print(f"Deposited: {amount}")
def get_balance(self):
return self.__balance
# Creating an object
account = BankAccount(1000)
[Link](500)
print(account.get_balance()) # Output: 1500
# Trying to access private attribute directly will give an error
# print(account.__balance) # AttributeError
2.2 Abstraction (Hiding Complexity)
Abstraction means hiding the implementation details and only exposing the necessary
functionalities.
Why?
• Reduces complexity
• Improves code usability
Example: When you use an ATM, you don’t need to know how it processes transactions
internally. You just insert your card, enter a PIN, and withdraw money.
from abc import ABC, abstractmethod
class Vehicle(ABC): # Abstract class
@abstractmethod
def start_engine(self):
pass # Method must be implemented by subclasses
class Car(Vehicle):
def start_engine(self):
print("Car engine started.")
# Creating object
my_car = Car()
my_car.start_engine() # Output: Car engine started.
Here, Vehicle is an abstract class that defines a general structure. Car implements the method.
2.3 Inheritance (Code Reusability)
Inheritance allows one class (child/subclass) to inherit the properties and behaviors of another
class (parent/superclass).
Why?
• Reduces code duplication
• Supports code reusability
Example:
A Car is a type of Vehicle, so we can create a general Vehicle class and let Car inherit from it.
class Vehicle:
def __init__(self, brand):
[Link] = brand
def drive(self):
print(f"{[Link]} is moving.")
# Car class inherits from Vehicle
class Car(Vehicle):
def honk(self):
print("Car horn is honking.")
# Creating an object of Car
my_car = Car("Honda")
my_car.drive() # Inherited method
my_car.honk() # Own method
Here, Car inherits the drive() method from Vehicle, avoiding redundant code.
2.4 Polymorphism (Multiple Forms)
Polymorphism allows the same method or function to behave differently based on the object
calling it.
Why?
• Increases flexibility
• Makes code more dynamic
Method Overriding (Child class redefines a method)
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self): # Overriding method
print("Dog barks")
# Creating objects
animal = Animal()
dog = Dog()
animal.make_sound() # Output: Animal makes a sound
dog.make_sound() # Output: Dog barks
Here, the make_sound() method behaves differently for Animal and Dog.
Method Overloading (Same method, different parameters)
Python doesn’t support method overloading directly, but it can be achieved using default
parameters:
class MathOperations:
def add(self, a, b, c=0): # Default argument for overloading
return a + b + c
math = MathOperations()
print([Link](2, 3)) # Output: 5
print([Link](2, 3, 4)) # Output: 9
3. Additional OOP Features
3.1 Constructor (__init__() method)
A special method in Python classes that runs automatically when an object is created.
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
person1 = Person("Alice", 25)
print([Link]) # Output: Alice
3.2 Destructor (__del__() method)
Used to free resources when an object is deleted.
class Example:
def __init__(self):
print("Object Created.")
def __del__(self):
print("Object Destroyed.")
obj = Example()
del obj # Output: Object Destroyed.
3.3 Static Methods
A method that belongs to a class but does not access instance attributes.
class Math:
@staticmethod
def square(x):
return x * x
print([Link](4)) # Output: 16
4. Advantages of OOP
Code reusability (via inheritance)
Data security (via encapsulation)
Code flexibility (via polymorphism)
Better software design and maintenance
5. Conclusion
OOP is a powerful approach that makes coding modular, reusable, and efficient. It is widely used
in languages like Python, Java, C++, C#, and JavaScript to build complex applications like
games, web apps, and enterprise software.