0
0

ポリモーフィズム

Posted at

はじめに

ポリモーフィズムについてまとめる

ポリモーフィズムとは

同名のメソッドで異なる挙動を実現する。
多態性と訳される。

参考コード

Figuer.php
class Figure
{
    protected float $width;
    protected float $height;

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

    public function getArea(): float
    {
        return 0;
    }
}

Triangle.php
require_once 'Figure.php';

class Triangle extends Figure
{
    public function getArea(): float
    {
        return $this->width * $this->height / 2;
    }
}
Square.php
require_once 'Figure.php';

class Square extends Figure
{
    public function getArea(): float
    {
        return $this->width * $this->height;
    }
}
polymo.php
require_once 'Triangle.php';
require_once 'Square.php';

$tri = new Triangle(5, 10);
$squ = new Square(5, 10);
print "三角形の面積: " . $tri->getArea() . "\n"; // 三角形の面積: 25
print "四角形の面積: " . $squ->getArea() . "\n"; // 四角形の面積: 50

Figureクラスを継承する2つのサブクラスTriangleSquareで同名のgetAreaメソッドをオーバーライドし、それぞれ三角形と四角形の面積を求めている。
複数のクラスで同じ名前のメソッドを定義している。

ポリモーフィズムのメリット

同じ目的の機能を呼び出すために異なる名前(命令)を覚えなくても良い点。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0