0
0

継承/オーバーライドの禁止

Posted at

はじめに

継承/オーバーライドの禁止についてまとめる

なぜ継承/オーバーライドを禁止するのか

継承可能なクラスには、実装/修正する際に派生クラスへの影響を考慮しなければならず、派生クラスの間でも、どのクラス/メソッドなら安全に継承/オーバーライドできるかを判別しなければならない。
このような問題を考えると、無制限に継承/オーバーライドを認めるのは避けるべきで、設計時点で継承/オーバーライドを想定していないならば、禁止してしまった方が良い。

final修飾子

継承/オーバーライドを禁止する

参考コード1

BusinessPersonクラスのworkメソッドをオーバーライド禁止にしている。

Person.php
class Person
{
    public $firstName;
    public $lastName;

    public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    public function show()
    {
        print "<p>私の名前は{$this->lastName}{$this->firstName}です。</p>";
    }
}
BusinessPerson.php
require_once 'Person.php';

class BusinessPerson extends Person
{
    public final function work(): void
    {
        print "<p>{$this->lastName}{$this->firstName}は働いています。</p>";
    }
}
HetareBusinessPerson.php
require_once 'BusinessPerson.php';

class HetareBusinessPerson extends BusinessPerson
{
    public function work(): void
    {
        parent::work();
        print "ただしボチボチと"; // 独自の処理
    }
}

参考コード2

BusinessPersonクラスへの継承を禁止している。

Person.php
class Person
{
    public $firstName;
    public $lastName;

    public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    public function show()
    {
        print "<p>私の名前は{$this->lastName}{$this->firstName}です。</p>";
    }
}
BusinessPerson.php
require_once 'Person.php';

final class BusinessPerson extends Person
{
    public function work(): void
    {
        print "<p>{$this->lastName}{$this->firstName}は働いています。</p>";
    }
}
HetareBusinessPerson.php
require_once 'BusinessPerson.php';

class HetareBusinessPerson extends BusinessPerson
{
    public function work(): void
    {
        parent::work();
        print "ただしボチボチと"; // 独自の処理
    }
}
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