You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Unlike method overriding, in method overloading the choice of which method to invoke is determined at compile time. Even if the run-time type differs for each invocation, in overloading, the method invocations depend on the type of the object at compile time.

Non-Compliant Code Example

This non-compliant example shows how the programmer can confuse overloading with overriding. At compile time, the type of the object array is Collection. The messages that one would typically expect are Set invoked, ArrayList invoked and Collection is not recognized. However, in all three instances Collection is not recognized gets displayed. This is because in overloading, the method invocations are not affected by the run-time types but only the compile time type (Collection). It is dangerous to implement overloading to tally with overriding, more so, because the latter is characterized by inheritance unlike the former.

public class Overloader {
  public static String display(Set s) {
    return "Set invoked";
  }

  public static String display(ArrayList l) {
    return "ArrayList invoked";
  }

  public static String display(Collection c) {
    return "Collection is not recognized";
  }

  public static void main(String[] args) {
    Collection[] invokeAll = new Collection[] {new HashSet(), new ArrayList(), new TreeSet()};

    for (int i = 0; i < invokeAll.length; i++)
      System.out.println(display(invokeAll[i]));
  }
}

Compliant Solution

This compliant solution uses a single display method and instanceof to distincguish between different types. The output is Set invoked, ArrayList invoked, Set invoked which is expected. Do not create ambiguity while using overloading so that the code is clean and easy to understand.

public class Overloader {

  public static String display(Collection c) {
    return (c instanceof Set ? "Set invoked" : (c instanceof ArrayList ? "ArrayList invoked" : "Collection is not recognized"));
  }

  public static void main(String[] args) {
    Collection[] invokeAll = new Collection[] {new HashSet(), new ArrayList(), new TreeSet()};

    for (int i = 0; i < invokeAll.length; i++)
      System.out.println(display(invokeAll[i]));
  }
}

References

JEPL, Item 26, Use overloading judiciously
Java Documentation http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html

  • No labels