Answers for "c# polymorphism"

C#
9

c# polymorphism

class Animal{
  public virtual void animalSound() {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig: Animal {
  public  override void animalSound() {//override superclass method
    Console.WriteLine("The pig says: wee wee");
  }
}

class Dog: Animal {
  public override void animalSound() {//override superclass method
    Console.WriteLine("The dog says: bow wow");
  }
}

static class main {
  static void Main(){
    //You can add all objects inherited from Animal to an Animal type list
    Animal[] animals = new Animal[3]; //Creating the Animal List
    animals[0] = new Animal(); //Add a new animal object to the list
    animals[1] = new Dog(); //Add a new dog object to the list
    animals[2] = new Pig(); //Add a pig object to the list
    foreach (Animal a in animals){
      a.animalSound(); //This statement prints the correct string no matter the class
    }
  }
}
Posted by: Guest on May-20-2020
0

polymorphism in c#

public class X  
{  
    public virtual void A()  
    {  
    }  
}  
public class Y : X  
{  
    public override void A()  
    {  
    }  
}
Posted by: Guest on March-03-2021

Code answers related to "c# polymorphism"

C# Answers by Framework

Browse Popular Code Answers by Language