【S4】問1解答例

<?php

/**
 * 抽象クラス
 */
abstract class Shape
{
    abstract public function calculateArea(): float;
}
                    
<?php

/**
 * Circleクラス
 */
class Circle extends Shape
{
    private int $radius;

    public function __construct(int $radius)
    {
        $this->radius = $radius;
    }

    public function calculateArea(): float
    {
        return M_PI * $this->radius * $this->radius;
    }
}
                    
<?php

/**
 * Rectangleクラス
 */
class Rectangle extends Shape
{
    private int $width;
    private int $height;

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

    public function calculateArea(): float
    {
        return $this->width * $this->height;
    }
}
                    
<?php

// Circle クラスを使用
$circle = new Circle(5);
echo '円の面積: ' . $circle->calculateArea() . PHP_EOL;

// Rectangle クラスを使用
$rectangle = new Rectangle(4, 6);
echo '長方形の面積: ' . $rectangle->calculateArea() . PHP_EOL;