Overloading

Overloading means that two methods in the same class have the same name but different parameters.

To explain this consider the following example. To work out the area of a triangle we could use (base*height)/2 or Heron's Formula. Both these methods work, but they use different parameters. We could write two static methods with different names, but given that both methods have the same task (calculating the area), it would be more logical to use the same name and let the program decide how to calculate the area. To achieve this write a Triangle class with the two methods:

public static double area(double side1, double side2, double side3)
{
//Calculation for area using Heron's Formula
return area;
}

public static double area(double base, double height)
{
//Calculate area using (base*height)/2
return area;
}

Then all we need to do to calculate the area is call these methods:

area = Triangle.area(4.5, 6.7, 3.5); to use Heron's formula

or

area = Triangle.area(6.2, 4.8); to use the (base*height)/2 method.

The program knows which method to use based on the parameters given.

Overloading is also allowed if the number of parameters are the same but only the type differs, so one method could be used for doubles and another for integers.

It is easy to confuse overloading with overriding. Remember that overloading provides for two methods with the same name but different parameters, while overriding refers to replacing or overwriting a method.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License