LoginSignup
0
0

インターフェイス

Posted at

はじめに

インターフェイスについてまとめる

インターフェイスとは

配下のメソッドが全て実装を期待/強制するメソッドであるクラスのこと。
中身を持つメソッドやプロパティを定義できず、アクセス修飾子の指定もできない。

インターフェイスと抽象クラスとの違い

インターフェイスでは多重継承ができる。
抽象クラスでは多重継承はできない。

多重継承が可能なことで、メソッドを目的に応じて様々なインターフェイスに振り分け、サブクラス側では必要なメソッドを含むインターフェイスだけを選択的に継承(正しくは実装)する、ということができる。

インターフェイスの役割

インターフェイスの利用者に契約内容を約束し、裏側の実装を隠す。
そして、実装者にはその契約を守ることを求める。

参考コード

TriangleクラスでIFigureインターフェイスを実装している。

IFigure.php
interface IFigure
{
    function getArea(): float;
}
Triangle.php
require_once 'Figure.php';

class Triangle implements IFigure
{
    protected float $width;
    protected float $height;

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

    public function getArea(): float
    {
        return $this->width * $this->height / 2;
    }
}
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