リスコフの置換原則に気を遣おう
掲載日: 2026/06/04 更新日: 2026/06/05
リスコフの置換原則に気を遣おう
リスコフの置換原則とは
リスコフの置換原則(りすこふのちかんげんそく、英: Liskov substitution principle)は、オブジェクト指向プログラミングにおいて、サブタイプのオブジェクトはスーパータイプのオブジェクトの仕様に従わなければならない、という原則である。リスコフの置換原則を満たすサブタイプを behavioral subtype(英語版) と呼ぶ。
wikipediaより引用
どういうこと?
継承(is-a)の関係にあるクラスは親クラス以上の機能を持ってはいけないということ
逆説的にはis-aの関係にないものを継承しないこと
例
‘’’
class Rectangle
{
public:
virtual void SetWidth(int Width)
{
this->Width = Width;
}.my-custom-style
virtual void SetHeight(int Height)
{
this->Height = Height;
}.my-custom-style
int GetArea() const
{
return Width * Height;
}.my-custom-style
protected:
int Width = 0;
int Height = 0;
}.my-custom-style ;
class Square : public Rectangle
{
public:
void SetWidth(int Width) override
{
this->Width = Width;
this->Height = Width;
}.my-custom-style
void SetHeight(int Height) override
{
this->Width = Height;
this->Height = Height;
}.my-custom-style
}.my-custom-style ;
‘’’
この場合
つまり…?
継承するときは厳密にis-a関係か注意しよう!
余談
この原則を提唱したBarbara Liskovさんは女性で御年 86歳とのこと



