using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } } class Cat : Animal { public override void Speak() { Console.WriteLine("Cat meows"); } } class Program { static void Main() { Animal myAnimal = new Dog(); myAnimal.Speak(); } }
The variable myAnimal is of type Animal but holds an instance of Dog. Because Speak is virtual and overridden in Dog, the Dog version runs, printing "Dog barks".
Polymorphism lets you write code that works on a base class type but actually runs the correct method for the real object type. This makes code flexible and reusable.
using System; class Shape { public virtual void Draw() { Console.WriteLine("Drawing a shape"); } } class Circle : Shape { public new void Draw() { Console.WriteLine("Drawing a circle"); } } class Program { static void Main() { Shape s = new Circle(); s.Draw(); } }
The Draw method in Circle uses new instead of override. This hides the base method rather than overriding it. Since s is of type Shape, the base class method runs, printing "Drawing a shape".
Option A correctly declares the base method as virtual and the derived method as override, enabling polymorphism.
Option A lacks virtual/override, so no polymorphism.
Option A is valid because the base class is declared abstract and the method is abstract.
Option A uses new which hides the method, not polymorphism.
using System; using System.Collections.Generic; abstract class Vehicle { public abstract void Start(); } class Car : Vehicle { public override void Start() { Console.WriteLine("Car started"); } } class Motorcycle : Vehicle { public override void Start() { Console.WriteLine("Motorcycle started"); } } class Program { static void Main() { List<Vehicle> vehicles = new List<Vehicle> { new Car(), new Motorcycle() }; foreach (var v in vehicles) { v.Start(); } } }
The list contains Car and Motorcycle objects, both overriding Start. The loop calls Start on each, printing their respective messages.