LoginSignup
1
1

More than 5 years have passed since last update.

オーバーライド

Posted at

オーバーライドとは

オーバーライドとは、スーパクラスから継承されたサブクラスにおいて、メンバ関数を独自の機能で上書きすることです。
例:


namespace Sales
{
    class Section
    {
        private string _title;
        public string Title
        {
            get
            {
                return _title;
            }
            set
            {
                _title = value;
            }
        }
        public byte Id { get; set; }

    public override int GetHashCode()
    {
        return Id;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        int a = GetHashCode();
        int b = obj.GetHashCode();
        bool r = (a == b);
        return r;
    }
    public override string ToString()
    {
        return Title;
    }

    static public bool operator ==(Section a, Section b)
    {
        if ((object)a == null) return ((object)b == null);
        return a.Equals(b);
    }
    static public bool operator !=(Section a, Section b)
    {
        if ((object)a == null) return ((object)b == null);
        return !a.Equals(b);
    }
}


}

上記の19行目~のメソッドはObjectクラスのメンバをオーバーライドしています。
オーバーライドしたい場合は宣言部にoverrideというキーワードを記述します。
ただし、すべてのメンバーがオーバーライドできるわけではなく、オーバーライドできる基本クラスのメンバーの宣言には「virtual」「abstract」「override」のいずれかが記述されている必要があります。
上で言っていますが今回の場合、ソースの中にあるものをオーバーライドしているわけではなく、Sectionクラスが暗に継承しているObjectクラスがオーバーライドされています。

Objectクラスとは

Objectクラスとは.NetFrameworkのクラス階層の基本クラスであり型階層のルートです。
基本的に継承を何も指定していないクラスはObjectクラスを指定したことになります。
っていうかすべてのクラスは例外なく暗黙的にObjectクラスを継承しています。

1
1
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
1
1