C# Polymorphism
Objectives
- What is Polymorphism ?
- Method overriding
- Abstract classes
- Interfaces
What is Polymorphism ?
The Polymorphism is a key concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass.
It enables flexibility and extensibility in software design by allowing methods to behave differently based on the object they are invoked on.
Method Overriding:
Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class.
The overridden method in the derived class must have the same signature (name, return type, and parameters) as the method in the base class.
It allows for runtime polymorphism, where the appropriate method implementation is determined dynamically based on the actual type of the object at runtime.
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
Abstract Classes:
Abstract classes are classes that cannot be instantiated directly and may contain one or more abstract methods.
Abstract methods are declared without implementation and must be implemented by derived classes.
Abstract classes can contain both abstract and non-abstract methods.
public abstract class Shape
{
public abstract double CalculateArea();
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
Interfaces
Interfaces are define a contract specifying a set of methods and properties that implementing classes must provide.
Interfaces cannot contain fields, constructors, or implementation code.
Interfaces enable polymorphism by allowing objects of different classes to be treated uniformly based on the interfaces they implement.
public interface IShape
{
double CalculateArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}