What is polymorphism?
Polymorphism means many forms that enable a single interface to work with different implementations. In other words, depending on the object on which it operates, the same method or function can do a variety of functions.
1. Using Inheritance
Inheritance is used to allow the class to inherit methods and attributes from its base class. Polymorphism can be performed using method overriding, as shown below
using System;
public class Car
{
public virtual void MakeColor()
{
Console.WriteLine("The car has a color");
}
}
public class Audi : Car
{
public override void MakeColor()
{
Console.WriteLine("The Audi is red");
}
}
public class Tesla : Car
{
public override void MakeColor()
{
Console.WriteLine("The Tesla is blue");
}
}
class Program
{
static void Main()
{
Car myAudi = new Audi();
Car myTesla = new Tesla();
myAudi.MakeColor();
myTesla.MakeColor();
Console.ReadKey();
}
}
In the program above, the MakeColor
method is overridden in the Audi
and Tesla
classes. When MakeColor
is called on a Car
reference pointing to an Audi
or Tesla
object, the override method is invoked.
Output:
The Audi is red
The Tesla is blue
2. Using Interfaces
Interfaces specify the rules that classes must follow. This enables different classes to use the same interface in various ways, displaying a different sort of polymorphism.
using System;
public interface ICar
{
void MakeColor();
}
public class Audi : ICar
{
public void MakeColor()
{
Console.WriteLine("The Audi is red");
}
}
public class Tesla : ICar
{
public void MakeColor()
{
Console.WriteLine("The Tesla is blue");
}
}
class Program
{
static void Main()
{
ICar myAudi = new Audi();
ICar myTesla = new Tesla();
myAudi.MakeColor();
myTesla.MakeColor();
Console.ReadKey();
}
}
In the above program, the ICar
interface defines a MakeColor
method. Both the Audi
and Tesla
classes implement this interface and provide their specific implementations of the MakeColor
method. The Main
method provides polymorphism by calling MakeColor
on objects of types Audi
and Tesla
through the ICar
interface reference.
Output:
The Audi is red
The Tesla is blue
Comments (0)