abstract class and interface class diference

 An abstract class in PHP is a class that cannot be instantiated directly and is meant to be extended by other classes. Abstract classes are used to define a blueprint for other classes to follow, providing common functionality that subclasses can inherit and override as needed. Here's an example of an abstract class and how it can be used:

<?php // Define an abstract class abstract class Shape { protected $color; public function __construct($color) { $this->color = $color; } // Abstract method to calculate area (to be implemented by subclasses) abstract public function calculateArea(); } // Concrete subclass Circle extending Shape class Circle extends Shape { private $radius; public function __construct($color, $radius) { parent::__construct($color); $this->radius = $radius; } // Implementing the abstract method to calculate area for Circle public function calculateArea() { return pi() * pow($this->radius, 2); } } // Concrete subclass Rectangle extending Shape class Rectangle extends Shape { private $width; private $height; public function __construct($color, $width, $height) { parent::__construct($color); $this->width = $width; $this->height = $height; } // Implementing the abstract method to calculate area for Rectangle public function calculateArea() { return $this->width * $this->height; } } // Create instances of concrete subclasses $circle = new Circle('red', 5); $rectangle = new Rectangle('blue', 4, 6); // Call the calculateArea method for each shape echo "Area of Circle: " . $circle->calculateArea() . " square units\n"; echo "Area of Rectangle: " . $rectangle->calculateArea() . " square units\n"; ?>

In this example:

  • Shape is an abstract class with a constructor and an abstract method calculateArea().
  • Circle and Rectangle are concrete subclasses that extend Shape and implement the calculateArea() method based on their specific shapes.
  • The __construct() method in each subclass calls the parent constructor (parent::__construct($color)) to set the color property inherited from Shape.

Abstract classes are useful for creating a hierarchy of related classes that share common behavior but have distinct implementations for certain methods. They promote code reusability and maintainability by defining a common interface for subclasses to follow.

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...