Wednesday, November 13, 2013

Overloading resolution in Java

Overloading is a very interesting topic in object oriented programming. As I know the what, when, why, and how, one more thing I didn’t know is the rule. Yes, there are rules defined on JVM how should resolved overloading method in JAVA. I got this piece of information when I was reading Programmer’s guide to SCJP. This is what mentions in the book:
The algorithm used by the compiler for the resolution of overloaded methods incorporates the following phases:
  1. It first performs overload resolution without permitting boxing, unboxing, or the use of a varargs call.
  2. If phase (1) fails, it performs overload resolution allowing boxing and unboxing, but excluding the use of a varargs call.
  3. If phase (2) fails, it performs overload resolution combining a varargs call, boxing, and unboxing.
When I first read on this, I never know such rules ever exist. Does this only happen to JAVA or it have been there since object oriented is invented? Anyhow, do not overlook on the rules mention above, there are priority when resolving overloading method. The condition define in first rule will always verify first before second and third rule is verify. If it fails, compiler will move on to the next rule, until it found a match. Consider following situation:
public static void funcA(String str, Object... obj) {    // (1)
 ...
}

public static void funcA(String str, Integer... i) {     // (2)
 ...
}
I have 2 overloading method at above code, if I do this:

funcA(“STRING”, 10, 10);

Compiler resolved the overloading method easily by picking up method (2). Now if I change this:
public static void funcA(String str, int x, Object... obj) {    // (1)
 ...
}

public static void funcA(String str, Integer... i) {            // (2)
 ...
}
This would bring trouble to the compiler as both overloading method could be the best fit, compiler unable to identify the most specific overloading method, thus compiler were force to issue an compile error to me.

No comments: