Java supports overloading methods and can distinguish between methods with different signatures. Consequently, with some qualifications, methods within a class can have the same name if they have different parameter lists. In method overloading, the method to be invoked at runtime is determined at compile time. Consequently, the overloaded method associated with the static type of the object is invoked even when the runtime type differs for each invocation.
For program understandability, do not introduce ambiguity while overloading (see MET50-J. Avoid ambiguous or confusing uses of overloading), and use overloaded methods sparingly [Tutorials 2013].
Noncompliant Code Example
This noncompliant code example attempts to use the overloaded
display() method to perform different actions depending on whether the method is passed an
ArrayList<Integer> or a
At compile time, the type of the object array is
List. The expected output is
List is not recognized (because
java.util.Vector is neither an
ArrayList nor a
LinkedList). The actual output is
ArrayList followed by
List is not recognized repeated three times. The cause of this unexpected behavior is that overloaded method invocations are affected only by the compile-time type of their arguments:
ArrayList for the first invocation and
List for the others.
This compliant solution uses a single
display method and
instanceof to distinguish between different types. As expected, the output is
List is not recognized:
Ambiguous uses of overloading can lead to unexpected results.
|[API 2013]||Interface Collection<E>|
|[Bloch 2008]||Item 41, "Use Overloading Judiciously"|
|[Tutorials 2013]||Defining Methods|