Method Overloading supports polymorphism because it is one way that Java implements one-interface, multiple methods paradigm.
To understand how, I consider the following. In languages that do not support method overloading,
each method must be given a unique name. However, frequently I will want to implement essentially
the same method for different types of data. Consider the absolute value function. In languages
that do not support overloading, there are usually 3 or more versions of this function, each with
a slightly different name. For instance in C, the function abs() returns the absolute value of an
integer, labs() returns the absolute value of an long integer, fabs() returns the absolute value
of an floating-point value. Since C does not support overloading, each function has to have its
own name, even though all 3 functions do essentially the same thing. This makes the situation
more complex, conceptually, than it actually is. Although the underlying concept of each function
is the same, I will have 3 names to remember. This situation doesn’t occur in Java, because each
absolute value method can use the same name. Indeed, Java’s standard class library includes an
absolute value method, called abs(). This method is overloaded by Java’s Math class to handle all
numeric types. Java determines which version of abs() to call based upon type of argument.
There is no rule stating that overload method must relate to one another. However from a stylistic point of view, method overloading implies a relationship. Thus, while I can use the same name to overload unrelated method, I think I should not. For example, I could have use the name sqr to create methods that return the square of an integer and the square root of a floating point value. But these 2 operations are fundamentally different. Applying method overloading in this manner is defeating its original purpose.
So in practice, should I only overload closely related operations? And any other reason to use overloaded methods besides this?
sqr
for both square and square root. This is not valid application for overloading, although syntactically it would work – CocoNess