抽象化の実践
メニューを表示するにはスワイプしてください
この課題では、以前の複数の章で見たことがあるかもしれないコードが与えられています。このコードには、MakeSound というオーバーライドされたメソッドが含まれています。
この課題は、Animal クラスを抽象クラスに変更し、MakeSound メソッドを abstract メソッドに変換することです。
この修正後も、プログラムの出力に変更がないことを確認してください。
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768using System; class Animal { protected string species; public Animal(string species) { this.species = species; } public virtual void MakeSound() { // Empty Method } public void DisplaySpecies() { Console.WriteLine($"Species: {species}"); } } class Cat : Animal { string furPattern; public Cat(string species, string furPattern) : base(species) { this.furPattern = furPattern; } public override void MakeSound() { Console.WriteLine("Meow! Meow!"); } } class Dog : Animal { float weight; public Dog(string species, float weight) : base(species) { this.weight = weight; } public override void MakeSound() { Console.WriteLine("Woof! Woof!"); } } class ConsoleApp { static void Main() { Animal myCat = new Cat("Feline", "Ginger & White"); Animal myDog = new Dog("Canine", 42.5f); myCat.DisplaySpecies(); myCat.MakeSound(); Console.WriteLine("\n"); myDog.DisplaySpecies(); myDog.MakeSound(); } }
abstractキーワードをAnimalクラス定義の前に追加し、抽象クラスにします。abstractキーワードをmakeSoundメソッドの戻り値の型の前に追加し、Animalクラス内でメソッドを抽象メソッドにします。次に、Animalクラスからメソッド本体を削除し、設計図(戻り値の型、メソッド名、引数)のみを残してください:returnType methodName(arg1, arg2, ..);
index.cs
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465using System; abstract class Animal { protected string species; public Animal(string species) { this.species = species; } public abstract void MakeSound(); public void DisplaySpecies() { Console.WriteLine($"Species: {species}"); } } class Cat : Animal { string furPattern; public Cat(string species, string furPattern) : base(species) { this.furPattern = furPattern; } public override void MakeSound() { Console.WriteLine("Meow! Meow!"); } } class Dog : Animal { float weight; public Dog(string species, float weight) : base(species) { this.weight = weight; } public override void MakeSound() { Console.WriteLine("Woof! Woof!"); } } class ConsoleApp { static void Main() { Animal myCat = new Cat("Feline", "Ginger & White"); Animal myDog = new Dog("Canine", 42.5f); myCat.DisplaySpecies(); myCat.MakeSound(); Console.WriteLine("\n"); myDog.DisplaySpecies(); myDog.MakeSound(); } }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 5. 章 9
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 5. 章 9