What is static or compile time polymorphism?
Static or compile-time polymorphism in object-oriented programming refers to a situation where the appropriate method or operator to be called is determined by the compiler at compile-time based on the number and types of arguments passed. This is achieved through method overloading and operator overloading.
This is one of the most frequently asked questions during interviews. This type of polymorphism is also known 'early binding'.
Let's illustrate this concept with a real-time example using method overloading in C#:
using System;
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
public string Add(string a, string b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
int result1 = calculator.Add(5, 10);
double result2 = calculator.Add(3.5, 2.8);
string result3 = calculator.Add("Hello, ", "world!");
Console.WriteLine("Result 1: " + result1);
Console.WriteLine("Result 2: " + result2);
Console.WriteLine("Result 3: " + result3);
}
}
In this example:
-
The Calculator class defines three overloaded 'Add' methods, each accepting different parameter types (integers, doubles, strings) but all named 'Add'.
- In the 'Main' method, an instance of the 'Calculator' class is created.
- The 'Add' methods are called with different arguments, and the compiler determines which version of the method to call based on the argument types.
- The results are then printed to the console.
When you run the program, you'll see the following output:
Result 1: 15
Result 2: 6.3
Result 3: Hello, world!
Even though all the methods are named 'Add', the appropriate version of the method to be called is determined at compile-time based on the argument types. This is an example of static or compile-time polymorphism, where the decision of which method to call is made by the compiler before the program runs.