派生クラス
メニューを表示するにはスワイプしてください
クラスが派生していると言う場合、それはそのクラスが親クラスのすべてのフィールドとメソッドを持ち、さらに派生クラス独自のフィールドやメソッドを追加できることを意味します。
ノート
派生クラス(子クラスとも呼ばれる)は、他のクラスのプロパティを継承するクラスです。これに対し、基底クラス(親クラスとも呼ばれる)は、継承される側のクラスです。
継承クラスを作成するための構文は次のとおりです。
index.cs
1234567891011// Base class (parent class) public class BaseClass { // Fields and methods of the base class } // Derived class (child class) public class DerivedClass : BaseClass { // Additional fields and methods specific to the derived class }
具体的なコード例は次のとおりです。
index.cs
12345678910111213141516171819202122232425262728293031323334353637using System; // Base class (parent class) public class Animal { public string Name; public void Eat() { Console.WriteLine($"{Name} is eating."); } } // Derived class (child class) public class Dog : Animal { public void Bark() { Console.WriteLine($"{Name} is barking."); } } class ConsoleApp { static void Main() { // Creating an instance of the derived class Dog myDog = new Dog(); myDog.Name = "Buddy"; // Using inherited method from the base class myDog.Eat(); // Using method specific to the derived class myDog.Bark(); } }
この例では、Dog は派生クラスであり、Animal 基底クラスから継承しています。Dog クラスは、Name クラスの Eat プロパティと Animal メソッドにアクセスできます。さらに、Bark クラス固有の新しいメソッド Dog が追加されています。
図に示されているように、あるクラスが他のクラスから継承しており、そのクラス自体もさらに別のクラスから継承している場合があります。
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445using System; // Base class public class Animal { public void Eat() { Console.WriteLine("Animal is eating."); } } // Intermediate class inheriting from Animal public class Mammal : Animal { public void GiveBirth() { Console.WriteLine("Mammal is giving birth."); } } // Derived class inheriting from Mammal public class Dog : Mammal { public void Bark() { Console.WriteLine("Dog is barking."); } } class Program { static void Main() { Dog myDog = new Dog(); // Methods from the base class myDog.Eat(); // Methods from the intermediate class myDog.GiveBirth(); // Methods from the derived class myDog.Bark(); } }
このような場合、最上位のクラスはスーパークラスと呼ばれます。この場合、Animal がスーパークラスです。複数の継承レベルが存在する場合は、多段階継承 と呼ばれます。
注意
一部の言語では、クラスが複数の基底クラスから継承することが可能であり、このような継承は 多重継承 と呼ばれます。C# では、クラスは1つの親クラスしか持てないため、多重継承はできません。
1. C# で派生クラスを宣言する際に使用されるキーワードまたは記号はどれですか?
2. 多重継承において、一番上に位置するクラスは何と呼ばれますか?
3. C#で多重継承は可能ですか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 1
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 1