C# Polymorphism
Polymorphism and Overriding Methods
Same name with different forms is the concept of polymorphism.
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
Polymorphism talks about flexibility.
Example:-
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Cat : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The cat says: meaaun");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
Example:-
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Cat : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The cat says: meaaun");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myCat.animalSound();
myDog.animalSound();
}
}
However, C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods.
Example:-
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Cat : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The cat says: meaaun");
}
}
class Dog : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myCat.animalSound();
myDog.animalSound();
}
}