該当のソースコード
php
1<?php 2 3abstract class Shape { 4 protected $color; 5 6 // サブクラスで共通にするプロパティー 7 public function __construct ($color = 'red') 8 { 9 $this->color = $color; 10 } 11 12 // サブクラスで共有できるメソッド 13 public function getColor () 14 { 15 return $this->color; 16 } 17 18 abstract protected function getArea(); // 何故宣言する必要がある? 19} 20 21class Square extends Shape { 22 protected $length = 4; 23 24 // 各形によって計算方が違うため、サブクラスに定義している 25 public function getArea() 26 { 27 return pow($this->length, 2); 28 } 29} 30 31class Triangle extends Shape { 32 protected $base = 4; 33 protected $height = 5; 34 35 // 各形によって計算方が違うため、サブクラスに定義している 36 public function getArea() 37 { 38 return .5 * $this->base * $this->height; 39 } 40} 41 42class Circle extends Shape { 43 protected $radius = 5; 44 45 // 各形によって計算方が違うため、サブクラスに定義している 46 public function getArea() 47 { 48 return M_PI * pow($this->radius, 2); 49 } 50} 51 52// インスタンス化するクラス名の部分を変えるだけで該当する形の面積が返ってくる 53echo (new Square)->getArea();
疑問
サブクラスで抽象メソッドを定義する場合、スーパークラスでそのことを宣言するのが一般的のようですが、
上記のようなコードの場合、サブクラスで定義する抽象メソッド(getArea()
)をスーパークラスで宣言(abstract protected function getArea();
)しなかったとしても、最終行のecho
の実行で問題は生じないかと思います。
ではなぜ宣言する必要があるのでしょうか。
必要性や目的をご教授下さい。よろしくお願い致します。
補足情報
PHP 7.0.30
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/18 12:45 編集
2018/06/18 13:07
2018/06/19 12:18