Open AidaHagh opened 3 months ago
public class Animal { // تعریف متد به صورت مجازی public virtual void MakeSound() { Console.WriteLine("Animal sound"); } }
public class Dog : Animal { // پیادهسازی مجدد متد در کلاس مشتق شده public override void MakeSound() { Console.WriteLine("Bark"); } }
public class Cat : Animal { // پیادهسازی مجدد متد در کلاس مشتق شده public override void MakeSound() { Console.WriteLine("Meow"); } }
class Program { static void Main() { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.MakeSound(); // Output: Bark myCat.MakeSound(); // Output: Meow } }
public class Rectangle {
public int Mohit(int x, int y) => (x + y) * 2;
public virtual int Masahat(int x, int y) => x * y;
} public class Square : Rectangle {
public int Mohit(int x) => x * 4;
public override int Masahat(int x, int y) // daynamic polymorphism
{
if (x != y) throw new Exception("Is Not Square"); or //return base.Masahat(x,y);
return x * x;
}
}
یک متد در کلاس پایه به صورت virtual تعریف میشود و در کلاس مشتق شده با استفاده از کلیدواژه override پیادهسازی مجدد میشود.