As was mentioned briefly in talking about Java Instance Methods, you can overload a Java method, just as you would overload a C++ function/method. (C doesn’t allow for overloading, only C++).
Since there is no method prototype, it is easy to just write your new method.
I like to group my overload methods together, so if I have a method called calcDistance(), with different types of parameters, I will group all of those together, so it’s easier to find in my source file. Java doesn’t require this, it is just good programming practice.
Like in C++, you cannot overload based upon a return type, only based upon the parameter list. You can have zero parameters for one method, or not, with multiple parameters and/or differing parameter data types in the other. Additionally, just like in C++, you have to make sure your data types are clear, and not ambiguous.
Below is an example of overloading a method:
public double calcDistance(Shape s1) {
// calculate distance based upon the two shapes distance from one another
}
public double calcDistance(double x, double y) {
// calculate the 2D distance based upon the x and y values passed to the method
}
public double calcDistance(double x, double y, double z) {
// calculate the 3D distance based upon the x, y, and z values passed to the method
}
Notice how just like with C++, the method name is exactly the same, only the parameters have changed.
Overloading Java Methods was originally found on Access 2 Learn
One Comment
Comments are closed.