0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

メソッドのオーバーライト

今回は継承の中のメソッドのオーバーライトについて解説したい。
アプリケーションを作っていく中で基底のクラスに定義されたメソッドでは機能が不足しそのままでは利用できない場合も考えられる。

そんなときはvirtualキーワードoverrideキーワードを使う必要がある。

基底クラスでvirtualキーワードを使いメソッドを定義すると、そのメソッドを派生クラスで上書きすることができる。

 class Person //基底クラス
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName
        {
            get { return LastName + FirstName; }
        }
        public string Email { get; set; }
        public virtual void Print() //virtualキーワードをつけると派生クラスでオーバーライトできる
        {
            Console.WriteLine($"名前: {FullName} {Email})");
        }
    }
    class Employee: Person //派生クラス
    { 
        public int Number { get; set; }
        public DateTime HireDate { get; set; }
        public override void Print() //overrideキーワードでメソッドを上書き定義
        {
            Console.WriteLine($"{Number}:{FullName} {Email} {HireDate.Year}年入社");
        }
    }

基底クラスでvirtualキーワードを使いメソッドを定義すると、そのメソッドを派生クラスで上書きすることができます。
このメソッドオーバーライドと言います。

public virtual void Print()

の部分がそれに当たります。

public override void Print()

の部分がオーバーライドしている箇所です。

class Program
    {
        static void Main(string[] args)
        {
            Practice_13_3_2();
        }
        public static void Practice_13_3_2()
        {
            var person= new Person
            {
                FirstName = "はるか",
                LastName = "佐々木",
                Email = "hsasaki@example.com"
            };
            person.Print();
            var employee = new Employee
            {
                Number = 132,
                FirstName = "涼太",
                LastName = "田中",
                Email = "rtanaka@exmple.com",
                HireDate = new DateTime(2015, 10, 1)
            };
            employee.Print();

        }
    }

結果は

名前: 佐々木はるか hsasaki@example.com)
132:田中涼太 rtanaka@exmple.com 2015年入社
となります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?