Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions.

An object represents a real-world entity and contains:

OOP helps developers build programs that are:

OOP is based on four fundamental principles:

1. Encapsulation

Encapsulation means bundling data and methods together inside a class and restricting direct access to some of the object’s data.

Purpose

Python Example

1
2
3
4
5
6
7
8
9
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance   # private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

Explanation

2. Abstraction

Abstraction means showing only essential features of an object while hiding implementation details.

Purpose

Python Example (Abstract Class)

1
2
3
4
5
6
7
8
9
10
11
from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def move(self):
        pass

class Car(Vehicle):
    def move(self):
        print("The car is moving")

Explanation

3. Inheritance

Inheritance allows a class (child) to reuse properties and methods from another class (parent).

Purpose

Python Example

1
2
3
4
5
6
7
class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

Explanation

4. Polymorphism

Polymorphism means one method name, multiple behaviors, depending on the object.

Purpose

Python Example

1
2
3
4
animals = [Dog(), Animal()]

for animal in animals:
    animal.speak()

Output

1
2
Dog barks
Animal makes a sound

Explanation