The word Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
While inheritance lets us inherit fields and methods from a parent class, polymorphism lets us modify those methods in the child classes so they can perform different tasks.
Imagine a base class called Animal with a method named AnimalSound(). Derived classes like Pig and Dog inherit this method. But what if we want the Pig to say "Wee wee" and the Dog to say "Bow wow"?
If we just create an AnimalSound() method in the child classes with the same name, C# will execute the base class method by default (or throw warnings).
virtual and override KeywordsTo allow a method to be customized by its child classes, you must:
virtual keyword to the method inside the Base Class.override keyword to the method inside the Derived Class.Let's look at the correct way to achieve Polymorphism:
using System;class Animal // Base class (parent) { // Use 'virtual' to allow overriding public virtual void AnimalSound() { Console.WriteLine("The animal makes a sound"); } }
class Pig : Animal // Derived class (child) { // Use 'override' to replace the base method public override void AnimalSound() { Console.WriteLine("The pig says: wee wee"); } }
class Dog : Animal // Derived class (child) { // Use 'override' to replace the base method public override void AnimalSound() { Console.WriteLine("The dog says: bow wow"); } }
class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create an Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.AnimalSound(); // Outputs: The animal makes a sound myPig.AnimalSound(); // Outputs: The pig says: wee wee myDog.AnimalSound(); // Outputs: The dog says: bow wow } }
Polymorphism is incredibly useful because you can write code that works with the generic base class (Animal), but at runtime, C# will automatically figure out exactly which overridden method (the Pig's or the Dog's) to call depending on the actual object type!
This makes your code highly scalable. If you add a Cat class tomorrow, you don't need to rewrite your main application logic; you just add the new class and override the sound method!
Note: You cannot override a method unless it is marked as virtual, abstract, or override in the parent class.
Which keyword must be used in the derived class to modify a virtual method from the base class?