Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked first NCE/CS and added two NCEs/CSs

...

Wiki Markup
This noncompliant example shows how the programmer can confuse overloading with overriding. At compile time, the type of the object array is {{CollectionList}}. The messagesoutput that one would typically expect areis {{Set invokedArrayList}}, {{ArrayList invokedLinkedList}} and {{CollectionList is not recognized}} ({{java.util.Vector}} does not inherit from {{java.util.List}}). However, in all three instances {{CollectionList is not recognized}} gets displayed. This ishappens because in overloading, the method invocations are not affected by the runtime types but only the compile time type ({{CollectionList}}). It is dangerous to implement overloading to tally with overriding, more so, because the latter is characterized by inheritance unlike the former. \[[Bloch 08|AA. Java References#Bloch 08]\]

Code Block
bgColor#FFCCCC
public class Overloader {
  private static String display(Set<Integer>ArrayList<Integer> sa) {
    return "Set invokedArrayList";
  }

  private static String display(ArrayList<String>LinkedList<String> l) {
    return "ArrayList invokedLinkedList";
  }

  private static String display(Collection<List<?> cl) {
    return "CollectionList is not recognized";
  }

  public static void main(String[] args) {
    Collection<List<?>[] invokeAll = new Collection<List<?>[] {new HashSet<Integer>ArrayList<Integer>(), 
    new ArrayList<String>LinkedList<String>(), new TreeSet<Integer>Vector<Integer>()};

    for(Collection<List<?> i : invokeAll) {
      System.out.println(display(i));
    }
  }
}

Compliant Solution

Wiki Markup
This compliant solution uses a single {{display}} method and {{instanceof}} to distinguish between different types. The output is {{SetArrayList, invokedLinkedList, ArrayListList invoked,is Setnot invokedrecognized}}, whichas is expected. Do As a general rule, do not introduce ambiguity while using overloading so that the code is clean and easy to understand. \[[Bloch 08|AA. Java References#Bloch 08]\]

Code Block
bgColor#ccccff
class Overloader {
public class Overloader {
  private static String display(Collection<List<?> cl) {
    return (cl instanceof SetArrayList ? "Set invokedArraylist" : (cl instanceof ArrayListLinkedList ? "ArrayList invokedLinkedList"
    : "CollectionList is not recognized"));
  }

  public static void main(String[] args) {
    Collection<List<?>[] invokeAll = new Collection<List<?>[] {new HashSet<Integer>ArrayList<Integer>(), 
    new ArrayList<String>LinkedList<String>(), new TreeSet<Integer>Vector<Integer>()};

    for(Collection<List<?> i : invokeAll) {
        System.out.println(display(i));
    }    
  }
}

Noncompliant Code Example

Notably, constructors cannot be overridden and can only be overloaded. Exercise Failure to exercise caution while passing arguments to them can create confusion since two overloadings can contain the same number of similarly typed parameters. This noncompliant example shows the constructor Con with three overloadings Con(int, String), Con(String, int) and Con(Integer, String). Overloading should also be avoided when the overloaded methods provide inconsistent functionality for arguments of different types. This example violates both these conditions.

Code Block
bgColor#FFCCCC

class Con {
  public Con(int i, String s) { /* Initialization Sequence #1 */ }
  public Con(String s, int i) { /* Initialization Sequence #2 */ } 
  public Con(Integer i, String s) { /* Initialization Sequence #3 */ } 
}

Compliant Solution

To be compliant, prefer the use of public static factory methods over 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 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 other, 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 in order to provide the checking functionality. This implementation can be extremely confusing to the client who will expect the getData() methods to behave identically and not variably, depending on whether an index of the record is specified or the retrievable value. Worse, in the presence of autoboxing, an innocent int argument may end up invoking the undesired overloading for Integer.

Code Block
bgColor#FFCCCC

class BadOverloading extends HashMap {
  HashMap<Integer,Integer> hm;
  public BadOverloading() {
    hm = new HashMap<Integer, Integer>();
    hm.put(1, 111990000); hm.put(2, 222990000); hm.put(3, 333990000);  // ssn records	  
  }
  public Integer getData(int i) { // overloading sequence #1
    return hm.get(i); // get record at position 'i'
  }
  public String getData(Integer i) { // overloading sequence #2
    String s = get(i).toString(); // get a particular record
    return (s.substring(0, 3) + "-" + s.substring(3, 5) + "-" + s.substring(5, 9));
	  
  }
  @Override public Integer get(Object data) {  // checks whether the ssn exists
    for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
      if(entry.getValue().compareTo((Integer)data) == 0)
        return entry.getValue();  // exists 
    }
    return null;
  }
  public static void main(String[] args) {
    BadOverloading bo = new BadOverloading();
    System.out.println(bo.getData(3)); // get record at index '3'
    System.out.println(bo.getData((Integer)111990000)); // get record containing data '111990000'
  }
}

Wiki Markup
Although the client will deduce such behavior sooner or later, other cases such as with the {{List}} interface may go unnoticed as \[[Bloch 08|AA. Java References#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.

Compliant Solution

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

Code Block
bgColor#ccccff

public Integer getDataByIndex(int i) { /* overloading  sequence #1 */ }
public String getDataByValue(Integer i) { /* overloading sequence #2 */ }

Risk Assessment

Ambiguous uses of overloading can lead to unexpected results.

...