Polymorphism is a key concept in object-oriented programming that allows us to create code that can work with objects of different types. The term “polymorphism” comes from Greek, meaning “many forms”, and refers to the ability of an object to take on many forms.
In C#, polymorphism can be achieved through method overriding and method overloading.
Method Overriding: Method overriding occurs when a derived class provides a specific implementation of a method that is already defined in its base class. Here’s an example:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Generic animal sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
public class Cat : Animal
{
public override void MakeSound(){
Console.WriteLine("Meow!");
}
}
In this example, we have a base class called “Animal” and two derived classes, “Dog” and “Cat”. Each derived class overrides the “MakeSound” method of the base class with its own implementation. We can create instances of these classes and call their “MakeSound” methods like this:
Animal myAnimal = new Animal();
Dog myDog = new Dog();
Cat myCat = new Cat();
myAnimal.MakeSound(); // Outputs "Generic animal sound"
myDog.MakeSound(); // Outputs "Woof!"
myCat.MakeSound(); // Outputs "Meow!"
In this example, we create an instance of each class and call its “MakeSound” method. Because each class has its own implementation of the “MakeSound” method, we get different outputs for each object.
Method overloading: allows us to define multiple methods with the same name but with different parameter lists. When a method is called, the compiler determines which method to call based on the number and types of the arguments passed. Here’s an example
public class MathUtils
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
}
In this example, the “MathUtils” class has two methods named “Add”, one that takes two integers and one that takes two doubles. When we call the “Add” method, the compiler determines which method to call based on the types of the arguments passed.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.