Object-Oriented Programming (OOP) Explained with Examples
What is object-oriented programming?
Object-oriented programming (OOP) is a way of structuring code around objects: bundles of data (attributes) and the behaviour that works on that data (methods). A class is the blueprint and each object is an instance of it. OOP relies on encapsulation, inheritance, polymorphism and abstraction to keep large programs organised, reusable and easier to change safely.
Key OOP terms: class, object, attribute and method
- Class: a blueprint that defines what data an object holds and what it can do, such as
BankAccount. - Object (instance): one concrete thing built from a class, such as the account belonging to Asha.
- Attribute (property): a piece of data stored on an object, such as
ownerorbalance. - Method: a function defined in a class that acts on the object, such as
deposit(). - Constructor: the special method that sets up a new object:
__init__in Python and__constructin PHP. - Interface: a contract listing methods a class promises to provide, without saying how.
OOP is a design approach, not a language feature you switch on. Python, PHP, Java, C# and JavaScript all support it, with different syntax for the same ideas. If you are new to code itself, start with the fundamentals of programming first.
Encapsulation: keep data and its rules together
Encapsulation means an object guards its own state. Outside code calls methods instead of changing data directly, so the rules (no negative deposits, no overdrawing) live in one place and cannot be skipped by accident.
class BankAccount:
def __init__(self, owner: str) -> None:
self.owner = owner
self._balance = 0 # leading underscore: internal, do not touch
@property
def balance(self) -> int: # read-only from outside
return self._balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount: int) -> None:
if amount <= 0 or amount > self._balance:
raise ValueError("Invalid withdrawal amount")
self._balance -= amount
account = BankAccount("Asha")
account.deposit(500)
account.withdraw(200)
print(account.balance) # 300Python relies on the underscore convention rather than enforced privacy. PHP enforces it with the private, protected and public keywords, and PHP 8.1 added readonly properties that can be set only once.
Inheritance, polymorphism and abstraction in Python
Inheritance lets a child class reuse and extend a parent class. Polymorphism means different classes respond to the same method call in their own way, so calling code does not need to know which class it has. Abstraction hides detail behind a simple, shared interface; an abstract base class defines the methods every child must implement.
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
def describe(self) -> str:
return f"{type(self).__name__} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Circle(Shape):
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return math.pi * self.radius ** 2
for shape in [Rectangle(3, 4), Circle(1)]:
print(shape.describe()) # Rectangle with area 12.00, Circle with area 3.14The loop treats every shape the same way, which is polymorphism in action. Trying to create Shape() directly raises a TypeError, because an abstract class cannot be instantiated. Our guide to classes and objects in Python covers the Python syntax in more depth.
The same ideas in PHP 8.3
This PHP example uses an interface, two implementations and constructor property promotion. OrderService depends only on the Notifier contract, so it works with email, SMS or any future channel.
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $message): void;
}
final class EmailNotifier implements Notifier
{
public function send(string $to, string $message): void
{
echo "Email to {$to}: {$message}\n";
}
}
final class SmsNotifier implements Notifier
{
public function send(string $to, string $message): void
{
echo "SMS to {$to}: {$message}\n";
}
}
final class OrderService
{
public function __construct(private readonly Notifier $notifier) {}
public function confirm(string $customer): void
{
// save the order here, then notify
$this->notifier->send($customer, 'Your order is confirmed.');
}
}
(new OrderService(new EmailNotifier()))->confirm('[email protected]');
(new OrderService(new SmsNotifier()))->confirm('9876543210');PHP frameworks such as Laravel are built on exactly this pattern. The PHP OOP guide covers traits, static members and namespaces.
Composition over inheritance
Inheritance models an "is a" relationship; composition models a "has a" relationship by giving an object other objects to work with. Deep inheritance trees become fragile because a change in a parent ripples into every child. Composition keeps parts small and swappable.
from typing import Protocol
class PowerSource(Protocol):
def start(self) -> str: ...
class PetrolEngine:
def start(self) -> str:
return "engine started"
class ElectricMotor:
def start(self) -> str:
return "motor humming"
class Car:
def __init__(self, power: PowerSource) -> None:
self.power = power
def drive(self) -> str:
return f"{self.power.start()}, car moving"
print(Car(PetrolEngine()).drive())
print(Car(ElectricMotor()).drive()) SOLID principles in brief
| Principle | Meaning in one line |
|---|---|
| Single responsibility | A class should have one reason to change. |
| Open/closed | Add behaviour by adding new code, such as a new Notifier, rather than editing working code. |
| Liskov substitution | A child class must work anywhere its parent is expected, without surprises. |
| Interface segregation | Prefer several small interfaces over one large one that forces empty methods. |
| Dependency inversion | Depend on abstractions (interfaces), not concrete classes, and pass dependencies in. |
Treat SOLID as guidance for reviewing a design, not rules to apply mechanically. A short script rarely needs five interfaces; the comparison in procedural versus object-oriented code shows when plain functions are enough.
Practical exercise: model a library loan system
- Write a
Bookclass with title, author and a private flag showing whether it is on loan. - Write a
Memberclass with a name and a list of borrowed books, limited to three. - Add
borrow()andreturn_book()methods that enforce the rules and raise clear errors. - Add a
Notifierinterface with an email version that prints a message when a book is borrowed, and pass it into aLibraryclass using composition. - Write the same design in PHP 8.3 using an interface and constructor property promotion.
You are done when outside code cannot change a loan flag directly, a fourth loan is refused, and swapping the notifier needs no change to Library. The Advanced PHP course applies these patterns to larger PHP applications.
Common mistakes
- Building deep inheritance chains to reuse a few lines, when a small helper object would be simpler.
- Making every property public, so any code can put an object into an invalid state.
- Creating "god classes" that handle database access, validation, formatting and email all at once.
- Overriding a parent method so that it behaves differently from what callers expect, breaking substitution.
- Adding interfaces and abstract classes before there is a second implementation that needs them.
Frequently asked questions
Is OOP better than procedural programming?
Neither is better in every case. OOP helps when a program models many related things with state and rules; small scripts are often clearer as plain functions.
What is the difference between an abstract class and an interface?
An interface only declares methods. An abstract class can also hold shared code and properties. In PHP a class can implement many interfaces but extend only one class.
Does JavaScript support OOP?
Yes. JavaScript uses prototypes underneath, and the class syntax added in ES2015 provides familiar classes, inheritance with extends and private fields marked with #.