به عنوان مثال ، به یک کلاس پایه به نام Animal فکر کنید که متدی به نام animalSound دارد. کلاسهای مشتق شده از حیوانات می تواند خوک ، گربه ، سگ ، پرنده باشد و آنها همچنین صدای خود را از حیوانات اجرا می کنند :
class Animal // Base class (parent) { public void animalSound() { Console.WriteLine("The animal makes a sound"); }}class Pig : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The pig says: wee wee"); }}class Dog : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The dog says: bow wow"); }}
ما از نماد : برای به ارث بردن از یک کلاس استفاده می کنیم.
اکنون می توانیم اشیا Pig و Dog را ایجاد کنیم و متد animalSound را روی هر دو مورد فراخوانی کنیم:
class Animal // Base class (parent) { public void animalSound() { Console.WriteLine("The animal makes a sound"); }}class Pig : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The pig says: wee wee"); }}class Dog : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The dog says: bow wow"); }}class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); }}
خروجی:
The animal makes a sound
The animal makes a sound
The animal makes a sound
خروجی مثال بالا احتمالاً همان چیزی نبود که انتظار داشتید. این به این دلیل است که متد کلاس پایه ، وقتی که آنها با یک نام مشترک هستند ، از متد کلاس مشتق شده غالب است.
با این حال ، سی شارپ با اضافه کردن کلمه کلیدی virtual به متد درون کلاس پایه و با استفاده از کلمه کلیدی override برای هر متد کلاس مشتق شده ، گزینه ای را برای جایگزینی متد کلاس پایه فراهم می کند:
class Animal // Base class (parent) { public virtual void animalSound() { Console.WriteLine("The animal makes a sound"); }}class Pig : Animal // Derived class (child) { public override void animalSound() { Console.WriteLine("The pig says: wee wee"); }}class Dog : Animal // Derived class (child) { public override void animalSound() { Console.WriteLine("The dog says: bow wow"); }}class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); }}
خروجی:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
چرا و چه زمانی باید از "وراثت" و "چند ریختی" استفاده شود؟
- برای قابلیت استفاده مجدد کد مفید است: هنگام ایجاد کلاس جدی ، از فیلدها و متدهای کلاس موجود استفاده مجدد کنید.