Method Overloading

From EggeWiki

Method overloadeding can be a bit tricky in Java, especially with inheritance. For example:

  public void foo(Object object) { System.out.println("I have an object: " + object); }
  public void foo(String string) { System.out.println("I have a string: " + string); }
  
  public void testOverloading() {
    foo(new Object());
    foo("test1");
    Object test2 = "test2";
    foo(test2);
  }

Yields:

I have an object: java.lang.Object@be0e27
I have a string: test1
I have an object: test2

Notice how the third call goes to the Object function. This is because the method dispatch is determined at compile time, and the compiler only sees 'test2' as an Object. It's a matter of opinion if autovars would improve the situatio. To make this more confusing, all you have to do is put foo(Object object) in a parent class. Because collections and iterators always return a type Object, it is easy to call the wrong function when using collections:

  public void testOverloading() {
    Set set = new HashSet();
    set.add(new Object());
    set.add("test3");
    for(Iterator iter = set.iterator(); iter.hasNext(); ) {
      foo(iter.next());
    }
  }

Yields:

I have an object: test3
I have an object: 3.14

If you want to have the correct function called, you'll have to do an instanceof check and some sort of case construct. In the case above, having multiple overloads of foo isn't a bad thing, since they do about the same action. Situations where the actions do something completely different should be avoided. Here's a particularly evil example:

  public float half(float f) { return f / 2; }
  public double half(double d) { throw new RuntimeException("Gotcha!"); }

  public void testOverloading3() {
    System.out.println(half(3)); <-- this works because 3 gets promoted to a float
    System.out.println(half(3.0)); <-- this fails because 3.0 is by default a double
  }

If you don't know all the data type rules in Java, it would be easy to call the wrong function here. I would go so far as to say the overloading is Syntactic Heroin, but I do think it should only be used to extreme care.