Object-Oriented Programming (OOP)

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 Car class 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 Vehicle class is a parent class that contains common properties and methods shared by different types of vehicles.
  • The Car class is a child class that inherits from the Vehicle class using the extends keyword. It adds its own property ($model) and method (getModel()), while also inheriting the properties and methods of the parent class.
  • The constructor of the Car class calls the constructor of the Vehicle class using parent::__construct() to initialize the inherited properties ($brand and $color) along with its own property ($model).
  • Objects of the Car class can access properties and methods defined in both the Car class and the Vehicle class, 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 Shape with a method calculateArea(). This method is intended to calculate the area of different shapes.
  • Two subclasses Circle and Rectangle inherit from the Shape class and override the calculateArea() method with their own implementations.
  • The calculateTotalArea() function demonstrates polymorphism by accepting an array of Shape objects. It iterates through each shape in the array and calls its calculateArea() 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 the Shape class, 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 Shape can be added without modifying the calculateTotalArea() 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 Shape class is an abstract class that contains a property $color and an abstract method calculateArea().
  • The Circle and Rectangle classes inherit from the Shape class and provide their own implementations for the calculateArea() method.
  • The Shape class defines a common interface for all shapes (via the calculateArea() method), while the subclasses provide the specific implementations.
  • Objects of the Circle and Rectangle classes 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();

?>
Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk