Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to respond to the same method call in different ways. It enables dynamic behavior and code flexibility, making programs more adaptable to different situations.
The Polymorphism Principle
Polymorphism stems from the Greek word "poly", meaning "many", and "morph", meaning "form". It refers to the ability of objects to take on many forms and respond to the same method call in different ways, based on their type or implementation.
Types of Polymorphism
Example: Shape Class Hierarchy
Consider a Shape class representing a generic shape:
class Shape {
// Abstract method
public abstract double GetArea();
}
Create derived classes Circle and Rectangle that inherit from the Shape class:
class
Circle : Shape {
private
double radius;
public
Circle(double radius) {
this.radius = radius;
}
public
override
double
GetArea() {
return Math.PI * radius * radius;
}
}
class
Rectangle : Shape {
private
double width;
private
double height;
public
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public
override
double
GetArea() {
return width * height;
}
}
Polymorphism in Action
Create an array of different Shape objects:
Shape[] shapes = new Shape[] { new Circle(5), new Rectangle(3, 4) };
Calculate the area of each shape using the GetArea() method:
foreach (Shape shape in shapes) {
double area = shape.GetArea();
Console.WriteLine("Area of " + shape.GetType().Name + ": " + area);
}
This code will print the area of each shape based on its specific implementation of the GetArea() method, demonstrating polymorphism.
Polymorphism Benefits
Conclusion
Polymorphism is a powerful feature of C# programming that enables dynamic behavior, code reusability, and code maintainability. It plays a crucial role in OOP principles, allowing programmers to create flexible and adaptable programs that can handle different data types and situations effectively. Understanding polymorphism is essential for developing high-quality C# applications.