KnowledgeBoat Logo
|

Computer Applications

Discuss how the best match is found when a call to an overloaded method is encountered. Give example(s) to support your answer.

User Defined Methods

1 Like

Answer

When an overloaded function is called, the compiler matches the signature in the function definitions with the arguments given in the method call statement and executes the function once the match is found.

To avoid ambiguity, we can use constant suffixes (F, L, D, etc.) to distinguish between values passed as arguments. These greatly help in indicating which overloaded function should be called. For example, an ordinary floating constant (e.g., 312.32) has the double type, while adding the F suffix (e.g., 312.32 F) makes it a float.

For example, the following code overloads a function perimeter() which calculates the perimeter of square, rectangle and trapezium.

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;
    }

    public static void main(String args[])  {
        Perimeter obj = new Perimeter();
        double areaSquare = obj.perimeter(5.8);
        double areaRectangle = obj.perimeter(10.5, 4.5);
        double areaTrapezium = obj.perimeter(4, 10, 7, 15);
        System.out.println(areaSquare + " " 
                            + areaRectangle + " " 
                            + areaTrapezium);
    }
}
Output
23.2 30.0 36.0

Answered By

1 Like


Related Questions