Polymorphism
Introduction to Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class. It enables flexibility and extensibility in software design.
Key Concepts
- Polymorphism: The ability of different classes to be treated as instances of the same class through inheritance.
- Method Overriding: Allows a subclass to provide a specific implementation of a method that is already defined in its superclass.
- Compile-time Polymorphism: Also known as method overloading, where multiple methods with the same name but different parameters are defined in a class.
- Runtime Polymorphism: Achieved through method overriding, where the method to be invoked is determined at runtime based on the type of object.
Example: Polymorphism in Action
Here's an example demonstrating runtime polymorphism in C#:
// Base class
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
// Derived class
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
// Another derived class
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows");
}
}
// Usage
Animal myAnimal = new Dog(); // Upcasting
myAnimal.MakeSound(); // Output: Dog barks
myAnimal = new Cat(); // Upcasting
myAnimal.MakeSound(); // Output: Cat meows
In this example, both Dog
and Cat
inherit from Animal
and override the MakeSound()
method to provide specific implementations. The method called is determined at runtime based on the actual type of the object.
Method Overloading
Method overloading allows multiple methods with the same name but different parameters to be defined in a class.
Example: Method Overloading
Using method overloading in C#:
public class Calculator
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(3, 5)); // Output: 8 (int version)
Console.WriteLine(calc.Add(2.5, 3.5)); // Output: 6.0 (double version)
In this example, the Add()
method is overloaded with different parameter types (int and double), allowing flexibility in calling the method with different argument types.
Conclusion
Polymorphism is a powerful concept in .NET that enhances code reusability and flexibility. Understanding polymorphism allows developers to design robust and extensible software systems.