Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 55
نمايش فراداده

4.7 Method Overload Resolution

Boxing and unboxing offer a lot of solutions to common problems (or, at least annoyances) in Java programming. However, these solutions manage to introduce a few quirks of their own, particularly in the area of method resolution. Method resolution is the process by which the Java compiler determines which method is being invoked. You'll need to be careful, as unboxing and boxing affect this process.

4.7.1 How do I do that?

In the normal case, Java handles method resolution by using the name of the method. In cases where a method is overloaded, though, an extra step must be taken. The arguments to the method are examined, and matched up with the arguments that a specific version of the requested method accepts. If no matching argument list is found, you get a compiler error. Sounds simple enough, right? Well, consider the following two methods:

public void doSomething(double num);

public void doSomething(Integer num);

Now supposed that you invoked doSomething( ):

int foo = 1;

doSomething(foo);

Which method is called? In a pre-Tiger environment, this is easy to determine. The int is widened to a double, and doSomething(double num) is called. However, in a Tiger environment, it would seem that boxing would occur, and doSomething(Integer num) would be what the method invocation would resolve to. While that's reasonable, it is not what happens.

Imagine writing a program like this, compiling and testing it in Java 1.4, and then recompiling it under Tiger. Suddenly, things start going haywire! Obviously, this isn't acceptable. For that reason, method resolution in Tiger will always select the same method that would have been selected in Java 1.4. As a rule, you really shouldn't mess around with this sort of overloading anyway, if at all possible. Be as specific as possible in your method naming and argument lists, and this issue goes away.

4.7.2 What just happened?

In Tiger, because of these restrictions, method resolution is a three-pass process:

The compiler attempts to locate the correct method without any boxing, unboxing, or vararg invocations. This will find any method that would have been invoked under Java 1.4 rules.

If the first pass fails, the compiler tries method resolution again, this time allowing boxing and unboxing conversions. Methods with varargs are not considered in this pass.

If the second pass fails, the compiler tries method resolution one last time, allowing boxing and unboxing, and also considers vararg methods.

These rules ensure that consistency with pre-Tiger environments is maintained.

NOTE

Varargs are detailed in Chapter 5.