Computer Applications

What is polymorphism? How does function overloading implement polymorphism?

User Defined Methods

2 Likes

Answer

Polymorphism is the property by which the same message can be sent to objects of several different classes and each object can respond in a different way depending on its class.

In function overloading, a function name has several definitions in the same scope. These function definitions are distinguished by their signatures. The same function behaves differently with different number and types of arguments.

Let us consider the given example in which the function perimeter() is overloaded. In each function, the perimeter of a different shape (square, rectangle and trapezium) is calculated.

public class Perimeter
{
    public double perimeter(double s)
    {
        double p = 4 * s;
        return p;
    }
    
    public double perimeter(double l, 
                            double b)
    {
        double p = 2 * (l + b);
        return p;
    }
    
    public double perimeter(double a, 
                            double b, 
                            double c, 
                            double d)
    {
        double p = a + b + c + d;
        return p;
    }
}

Thus, overloading implements polymorphism.

Answered By

2 Likes


Related Questions