1
2

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#入門・初心者】継承【オブジェクト指向】

1
Posted at

継承

継承とは、既存のクラス(親クラス)の性質(フィールド、メソッド、プロパティなど)を、新しいクラス(子クラス)に引き継ぐ仕組み。

  • 基本クラス(親クラス / スーパークラス):共通機能を提供する元のクラス
  • 派生クラス(子クラス / サブクラス):親の機能を受け継ぎ、さらに独自の機能を追加・修正したクラス
// 親クラス
public class Animal
{
    public string Name { get; set; }
    public void Eat() => Console.WriteLine("食事をします");
}

// 子クラス(Animalを継承)
public class Dog : Animal
{
    public void Bark() => Console.WriteLine("ワンワン!");
}
  • 使いすぎ注意。子クラスを理解するには親クラスまで理解する必要がある。継承が深くなると理解しづらくなる
  • 極力インターフェースを利用する

使いどころ

  • 抽象クラス:インターフェースではロジックを記述できないが、親クラスにはロジックを記述できるので、共通するロジックを親クラスでまとめて記述する
  • コントロールの拡張:Microsoftが提供しているTextBoxなどを継承して独自仕様にカスタマイズする
  • ベース画面の継承:ベース画面に共通となるUI(プログレスバーやロゴなど)を記述しておき、各画面はベース画面を継承して使用する
抽象クラス
public abstract class Shape
{
    // 抽象メソッド(子クラスで実装を強制)
    public abstract double GetArea();

    // 通常のメソッド(共通処理を提供)
    public void Display() => Console.WriteLine("図形を表示します");
}

public class Circle : Shape
{
    public double Radius { get; set; }
    // 抽象メソッドを具体的に実装
    public override double GetArea() => Math.PI * Radius * Radius;
}
1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?