Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits; made more normative

Method and constructor overloading allows one of two or more methods or constructors with the same name to be invoked, depending on the types of their arguments. The compiler inspects a call to an overloaded method or constructor and, using the declared types of the method parameters, decides which method to use. Consequently overloaded methods are quite useful. In some cases, however, ambiguity may arise because of the presence of relatively newer language features such as autoboxing and generics.

Furthermore, methods or constructors with the same parameter types that just differ only in their declaration order, are typically not flagged by Java compilers. This can be potentially error prone result in errors if a developer does not consult the documentation at every use of the method or constructor. A related pitfall is to associate differing semantics with each of the overloaded methods or constructors. Defining different semantics sometimes necessitates different orderings of the same method parameters, creating a vicious circle. Consider for example a getDistance() method whose one overloading returns the distance traveled from the source while another (with rearranged parameters) returns the uncovered distance to the destination. An implementer may not realize the difference unless the documentation is consulted at every use. This recommendation also applies to constructors as they can also be overloaded.

Noncompliant Code Example

Notably, constructors Constructors cannot be overridden and can only be overloaded. This noncompliant code example shows the constructor Con with three overloadings Con(int, String), Con(String, int) and Con(Integer, String).

...

Failure to exercise caution while passing arguments to them these constructors can create confusion as two these overloadings can contain the same number of similarly typed parameters. Overloading should must also be avoided when the overloaded constructors or methods provide inconsistent functionality for arguments of the same types, differing just in their declaration order. This noncompliant code example violates both these conditions.

Compliant Solution

To be compliant, prefer the use of This compliant solution uses public static factory methods over instead of public class constructors.

Code Block
bgColor#ccccff
public static void ConName1(int i, String s) { /* Initialization Sequence #1 */ }
public static void ConName2(String s, int i) { /* Initialization Sequence #2 */ }
public static void ConName3(Integer i, String s) { /* Initialization Sequence #3 */ }

Noncompliant Code Example

This program provides another concrete example of noncompliance. The In this noncompliant code example, the InformationLeak class holds a HashMap instance and returns a particular record to the caller based on either its key value in the map or the actual mapped value. The getData() method has been overloaded to return the contained data indexed by the key value in one case, whereas in the otherthe former case. In the latter case, it checks whether a particular record exists before formatting and returning it as a String object. The InformationLeak class inherits from java.util.HashMap and overrides its get() method to provide the checking functionality. This implementation can be extremely confusing to the client who will expect the getData() methods to behave identically in a similar fashion and not variably, depending depend on whether an index of the record is specified or the value to be retrieved.

WorseA further problem is that, in the presence of autoboxing, an int argument may end up invoking invoke the undesired overloading for Integer. This can happen if the overloading with the primitive int type is added to a class at a later date. Clients who expect the getData() method to fetch data based on its value will suddenly start invoking the new overloading whenever an int argument is passed and proceed to return the record by index. This happens because a primitive argument becomes more specific in the new version whereas in the old one, autoboxing allows the selection of the method with the Integer type parameter when an int is passed.

...

Wiki Markup
Although the client programmer might willeventually deduce such behavior sooner or later, other cases such as with the {{List}} interface may go unnoticed as Bloch \[[Bloch 2008|AA. Bibliography#Bloch 08]\] describes:

... the List<E> interface has two overloadings of the remove method: remove(E) and remove(int). Prior to release 1.5 when it was "generified", the List interface had a remove(Object) method in place of remove(E), and the corresponding parameter types, Object and int, were radically different. But in the presence of generics and autoboxing, the two parameter types are no longer radically different.

Consequently, a client programmer may not realize that the wrong element has been removed from the list.

...

Naming the two related methods differently disqualifies the overloading and is highly recommended in this caseeliminates overloading.

Code Block
bgColor#ccccff
public Integer getDataByIndex(int i) { /* overloadingno longer sequenceoverloaded #1 */ }
public String getDataByValue(Integer i) { /* overloadingno sequencelonger #2overloaded */ }

Risk Assessment

Ambiguous uses of overloading can lead to unexpected results.

...