Object-Oriented Programming (OOP): OOP is a programming paradigm that organizes software design around objects and data, rather than functions and logic. It focuses on the concept of “objects,” which are instances of classes that encapsulate data and behavior.
- Encapsulation: Encapsulation is the bundling of data and methods that operate on the data into a single unit or class. It helps in hiding the internal state of an object and only exposing the necessary functionalities.
- Inheritance: Inheritance allows a class (subclass/child) to inherit properties and behaviors (methods) from another class (superclass/parent). It promotes code reusability and the creation of a hierarchy of classes.
- Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility and extensibility in code by allowing methods to be overridden in subclasses.
- Abstraction: Abstraction is the process of hiding complex implementation details and showing only the necessary features of an object. It helps in managing complexity and improving understandability.
Let’s take a look at each feature one at a time, starting with Encapsulation. Since my backend skills are in PHP I will be presenting an example in PHP.
Encapsulation
In following example:
- The
Carclass encapsulates the properties ($brand,$model,$color) and provides getter and setter methods to access and modify these properties. - The properties are declared as
private, meaning they cannot be accessed directly from outside the class. This ensures data encapsulation and protects the internal state of the object. - Getter methods (
getBrand(),getModel(),getColor()) allow retrieving the values of the private properties. - Setter methods (
setBrand(),setModel(),setColor()) allow modifying the values of the private properties. - By using getter and setter methods, we can control how the properties are accessed and modified, enforcing encapsulation and maintaining the integrity of the object’s state.
<?php
class Car {
private $brand;
private $model;
private $color;
// Constructor
public function __construct($brand, $model, $color) {
$this->brand = $brand;
$this->model = $model;
$this->color = $color;
}
// Getter methods
public function getBrand() {
return $this->brand;
}
public function getModel() {
return $this->model;
}
public function getColor() {
return $this->color;
}
// Setter methods
public function setBrand($brand) {
$this->brand = $brand;
}
public function setModel($model) {
$this->model = $model;
}
public function setColor($color) {
$this->color = $color;
}
}
// Create a new Car object
$car = new Car("Toyota", "Camry", "Red");
// Accessing properties directly (not recommended due to encapsulation)
// $car->brand = "Honda"; // This won't work because the property is private
// Accessing properties using getter methods
echo "Brand: " . $car->getBrand() . "<br>";
echo "Model: " . $car->getModel() . "<br>";
echo "Color: " . $car->getColor() . "<br>";
// Modifying properties using setter methods
$car->setBrand("Honda");
$car->setModel("Accord");
$car->setColor("Blue");
// Display updated values
echo "<br>Updated Values:<br>";
echo "Brand: " . $car->getBrand() . "<br>";
echo "Model: " . $car->getModel() . "<br>";
echo "Color: " . $car->getColor() . "<br>";
?>
Inheritance
In this example:
- The
Vehicleclass is a parent class that contains common properties and methods shared by different types of vehicles. - The
Carclass is a child class that inherits from theVehicleclass using theextendskeyword. It adds its own property ($model) and method (getModel()), while also inheriting the properties and methods of the parent class. - The constructor of the
Carclass calls the constructor of theVehicleclass usingparent::__construct()to initialize the inherited properties ($brandand$color) along with its own property ($model). - Objects of the
Carclass can access properties and methods defined in both theCarclass and theVehicleclass, demonstrating inheritance in action.
<?php
// Parent class
class Vehicle {
protected $brand;
protected $color;
// Constructor
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Getter methods
public function getBrand() {
return $this->brand;
}
public function getColor() {
return $this->color;
}
}
// Child class inheriting from Vehicle
class Car extends Vehicle {
private $model;
// Constructor
public function __construct($brand, $model, $color) {
parent::__construct($brand, $color);
$this->model = $model;
}
// Getter method specific to Car class
public function getModel() {
return $this->model;
}
}
// Create a new Car object
$car = new Car("Toyota", "Camry", "Red");
// Accessing properties using getter methods
echo "Brand: " . $car->getBrand() . "<br>";
echo "Model: " . $car->getModel() . "<br>";
echo "Color: " . $car->getColor() . "<br>";
?>
Polymorphism
In this example:
- There’s a parent class
Shapewith a methodcalculateArea(). This method is intended to calculate the area of different shapes. - Two subclasses
CircleandRectangleinherit from theShapeclass and override thecalculateArea()method with their own implementations. - The
calculateTotalArea()function demonstrates polymorphism by accepting an array ofShapeobjects. It iterates through each shape in the array and calls itscalculateArea()method, regardless of whether it’s a circle or a rectangle. This is possible because each object in the array is treated as an instance of theShapeclass, but the actual method called depends on the type of object (dynamic dispatch). - Polymorphism allows for more flexible and extensible code, as new subclasses of
Shapecan be added without modifying thecalculateTotalArea()function.
<?php
// Parent class
class Shape {
// Method to calculate area (to be overridden by subclasses)
public function calculateArea() {
return 0;
}
}
// Subclass Circle inheriting from Shape
class Circle extends Shape {
private $radius;
// Constructor
public function __construct($radius) {
$this->radius = $radius;
}
// Overriding the calculateArea method for Circle
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
// Subclass Rectangle inheriting from Shape
class Rectangle extends Shape {
private $length;
private $width;
// Constructor
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
// Overriding the calculateArea method for Rectangle
public function calculateArea() {
return $this->length * $this->width;
}
}
// Function to calculate total area of shapes
function calculateTotalArea($shapes) {
$totalArea = 0;
foreach ($shapes as $shape) {
$totalArea += $shape->calculateArea();
}
return $totalArea;
}
// Create an array of shapes (circles and rectangles)
$shapes = array(
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
);
// Calculate the total area of shapes
$totalArea = calculateTotalArea($shapes);
echo "Total area of shapes: " . $totalArea;
?>
Abstraction
In this example:
- The
Shapeclass is an abstract class that contains a property$colorand an abstract methodcalculateArea(). - The
CircleandRectangleclasses inherit from theShapeclass and provide their own implementations for thecalculateArea()method. - The
Shapeclass defines a common interface for all shapes (via thecalculateArea()method), while the subclasses provide the specific implementations. - Objects of the
CircleandRectangleclasses can be created and used without knowing the exact implementation details of how the area calculation is done. This demonstrates abstraction, as the user interacts with the shapes at a higher level without needing to understand the internal workings of each shape.
<?php
// Abstract class representing a Shape
abstract class Shape {
protected $color;
// Constructor
public function __construct($color) {
$this->color = $color;
}
// Abstract method to calculate area
abstract public function calculateArea();
}
// Subclass Circle inheriting from Shape
class Circle extends Shape {
private $radius;
// Constructor
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
// Implementing the calculateArea method for Circle
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
// Subclass Rectangle inheriting from Shape
class Rectangle extends Shape {
private $length;
private $width;
// Constructor
public function __construct($color, $length, $width) {
parent::__construct($color);
$this->length = $length;
$this->width = $width;
}
// Implementing the calculateArea method for Rectangle
public function calculateArea() {
return $this->length * $this->width;
}
}
// Create objects of Circle and Rectangle
$circle = new Circle("Red", 5);
$rectangle = new Rectangle("Blue", 4, 6);
// Calculate and display areas
echo "Area of circle: " . $circle->calculateArea() . "<br>";
echo "Area of rectangle: " . $rectangle->calculateArea();
?>


