w3resource

PHP Class Shape: Abstract method and subclass implementation


3. Abstract Shape with Subclasses

Write a PHP class called 'Shape' with an abstract method 'calculateArea()'. Create two subclasses, 'Triangle' and 'Rectangle', that implement the 'calculateArea()' method.

Sample Solution:

PHP Code :

<?php
abstract class Shape {
    abstract public function calculateArea();
}

class Triangle extends Shape {
    private $base;
    private $height;

    public function __construct($base, $height) {
        $this->base = $base;
        $this->height = $height;
    }

    public function calculateArea() {
        return 0.5 * $this->base * $this->height;
    }
}

class Rectangle extends Shape {
    private $length;
    private $width;

    public function __construct($length, $width) {
        $this->length = $length;
        $this->width = $width;
    }

    public function calculateArea() {
        return $this->length * $this->width;
    }
}

$triangle = new Triangle(5, 7);
echo "Triangle Area: " . $triangle->calculateArea() . "</br>";

$rectangle = new Rectangle(4, 6);
echo "Rectangle Area: " . $rectangle->calculateArea() . "</br>";

?>

Sample Output:

Triangle Area: 17.5
Rectangle Area: 24

Flowchart:

Flowchart: Abstract method and subclass implementation.
Flowchart: Abstract method and subclass implementation.

For more Practice: Solve these Related Problems:

  • Write a PHP abstract class with multiple abstract methods, then implement these methods in several geometric shape subclasses.
  • Write a PHP program that creates an array of different Shape objects and calculates the total combined area.
  • Write a PHP script that uses polymorphism to call the calculateArea() method on various Shape subclass instances.
  • Write a PHP program that compares the areas of a Triangle and a Rectangle object created from the same set of dimensions.

Go to:


PREV : Circle Class.
NEXT : Resizable Interface with Square Class.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.