Introduction
Polymorphism lets us use one name for different actions. It helps make code simpler and easier to change.
Jump into concepts and practice - no test required
Polymorphism lets us use one name for different actions. It helps make code simpler and easier to change.
public class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("Meow"); } }
virtual means the method can be changed in child classes.
override means the child class changes the parent's method.
Animal myAnimal = new Dog(); myAnimal.Speak(); // Output: Bark
Animal myAnimal = new Cat(); myAnimal.Speak(); // Output: Meow
List<Animal> animals = new List<Animal> { new Dog(), new Cat() }; foreach (var animal in animals) { animal.Speak(); }
This program shows how different animals speak differently using the same method name.
using System; using System.Collections.Generic; public class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("Meow"); } } public class Program { public static void Main() { List<Animal> animals = new List<Animal> { new Dog(), new Cat(), new Animal() }; foreach (var animal in animals) { animal.Speak(); } } }
Polymorphism helps keep code flexible and easy to extend.
It works best with inheritance and method overriding.
Without polymorphism, you would need many if-else checks for types.
Polymorphism lets one method name work for different types.
It makes code easier to write, read, and change.
It is a key idea in object-oriented programming.
class Animal { public virtual string Speak() => "..."; }
class Dog : Animal { public override string Speak() => "Woof"; }
class Cat : Animal { public override string Speak() => "Meow"; }
Animal a = new Dog();
Console.WriteLine(a.Speak());class Shape { public void Draw() { Console.WriteLine("Shape"); } }
class Circle : Shape { public void Draw() { Console.WriteLine("Circle"); } }
Shape s = new Circle();
s.Draw();