Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 抽象化の実践 | OOP原則
C#オブジェクト指向構造

book抽象化の実践

メニューを表示するにはスワイプしてください

この課題では、以前の複数の章で見たことがあるかもしれないコードが与えられています。このコードには、MakeSound というオーバーライドされたメソッドが含まれています。

この課題は、Animal クラスを抽象クラスに変更し、MakeSound メソッドを abstract メソッドに変換することです。

この修正後も、プログラムの出力に変更がないことを確認してください。

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
using 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(); } }
  1. abstract キーワードを Animal クラス定義の前に追加し、抽象クラスにします。
  2. abstract キーワードを makeSound メソッドの戻り値の型の前に追加し、Animal クラス内でメソッドを抽象メソッドにします。次に、Animal クラスからメソッド本体を削除し、設計図(戻り値の型、メソッド名、引数)のみを残してください:returnType methodName(arg1, arg2, ..);
index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
using 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に質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  9
some-alt