Complete the code to declare a base class method that can be overridden.
public class Animal { public virtual void Speak() { Console.[1]("Animal speaks"); } }
The Console.WriteLine method prints text to the console. It is used here to show the base class message.
Complete the code to override the Speak method in the derived class.
public class Dog : Animal { public override void [1]() { Console.WriteLine("Dog barks"); } }
The derived class overrides the base class method named Speak to provide its own behavior.
Fix the error in calling the Speak method using a base class reference to a derived class object.
Animal myAnimal = new Dog();
myAnimal.[1]();The base class reference calls the Speak method, which is overridden by the derived class. This demonstrates runtime polymorphism.
Fill both blanks to create a base class reference to a derived class object and call the overridden method.
Animal [1] = new [2](); [1].Speak();
The variable myAnimal is declared as type Animal but refers to a new Dog object. Calling Speak uses the overridden method in Dog.
Fill all three blanks to implement runtime polymorphism with two derived classes overriding the base method.
public class Cat : Animal { public override void [1]() { Console.WriteLine("Cat meows"); } } Animal [2] = new Dog(); Animal [3] = new Cat(); [2].Speak(); [3].Speak();
The Cat class overrides Speak. Two variables of type Animal refer to Dog and Cat objects. Calling Speak on each shows runtime polymorphism.