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?

【C#】継承とは?

Posted at

継承とは?

継承とは、あるクラスの機能を別のクラスに引き継ぐ仕組みのことです。
共通部分をまとめて、再利用できるようにします。

例:人間 → 学生

// 親クラス(基底クラス)
class Person
{
    public string Name { get; set; }

    public Person(string name)  // ← コンストラクタ
    {
        Name = name;
        Console.WriteLine("Personのコンストラクタが呼ばれました");
    }

    public void Greet()
    {
        Console.WriteLine($"こんにちは、{Name}です。");
    }
}

// 子クラス(派生クラス)
class Student : Person
{
    public string School { get; set; }

    public Student(string name, string school) : base(name)
    {
        // base(name) → 親クラスのコンストラクタを呼び出す!
        School = school;
        Console.WriteLine("Studentのコンストラクタが呼ばれました");
    }

    public void Study()
    {
        Console.WriteLine($"{Name}{School}で勉強しています。");
    }
}

// 実行
var s = new Student("太郎", "C#大学");
s.Greet();
s.Study();

出力結果

Personのコンストラクタが呼ばれました
Studentのコンストラクタが呼ばれました
こんにちは、太郎です。
太郎はC#大学で勉強しています。

コンストラクタの流れ

  1. 子クラス (Student) が生成される
  2. まず親クラス (Person) のコンストラクタが実行される
  3. そのあとに子クラスのコンストラクタが実行される

つまり、
親 → 子 の順番で初期化される
これによって、親クラスで定義した共通の初期化処理が自動的に呼ばれるわけです。

ポイント

キーワード 意味
base 親クラスを指すキーワード。コンストラクタ呼び出しや親メソッドの利用に使う。
this 自分自身のインスタンスを指す。親とは無関係。

まとめ

  • 継承は「親クラスの機能を子クラスに引き継ぐ」仕組み
  • : 親クラス名 で継承できる
  • 親のコンストラクタは子より先に呼ばれる
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?