クラスの応用 / ch04 — 抽象クラス (abstract) / 演習 01

📝 ドリル 01 — abstract Shape を継承した Circle

問題

abstract class Shape を定義してください。

  • abstract public function area(): float; を宣言する (中身は書かない)

Shape を継承した Circle クラスを定義してください。

  • プロパティ r (float) を持つ
  • area() を実装して r * r * 3.14 を返す

半径 2.0Circle を作って area() の結果を 1 行出力してください。

期待される出力:

12.56

採点

php scripts/grade.php v2/topics/09-class-advanced/ch04-abstract/drill/01-abstract-shape/

ヒント

  • abstract class Shape { abstract public function area(): float; }
  • class Circle extends Shape { ... }
  • echo $c->area() . "\n";

テストケース

期待される出力

12.56

📄 starter.php(雛形)

このコードから書き始めてください。

<?php

// TODO: abstract class Shape を定義し、abstract public function area(): float; を宣言する

// TODO: Shape を継承した Circle クラスを定義する
//   - public float $r;
//   - public function area(): float { return $this->r * $this->r * 3.14; }

// TODO: r = 2.0 の Circle を作って area() の結果を出力する
✅ 解答例を見る(自分で解いてから)
<?php

abstract class Shape {
    abstract public function area(): float;
}

class Circle extends Shape {
    public float $r;

    public function area(): float {
        return $this->r * $this->r * 3.14;
    }
}

$c = new Circle();
$c->r = 2.0;
echo $c->area() . "\n";