Back to Top

Wednesday, March 10, 2010

Java import statement gotcha

190774444_2687512fb9_o There is a lot of debate on the intertubes if one should or shouldn’t use wildcard imports. I’m mostly indifferent to the discussion (mainly because all the package references are resolved compile time – so there is no performance overhead – and because today's IDE’s contain a lot of smarts to help you figure out which is the actual class being referenced), but here is something interesting I discovered recently:

Lets say that we have two classes with the same name in different packages:

package foo;

public class Foo {
	public static void print() {
		System.out.println("Foo");
	}
}
package bar;

public class Foo {
	public static void print() {
		System.out.println("Bar");
	}
}

Now create a test class in the bar package:

package bar;

import foo.*;

public class Test {
	public static void main(String[] args) {
		Foo.print();
	}
}

Question: what will this class print out? The answer is – surprisingly for me - “Bar”. It seems that the Java compiler (tested with 1.6u18, but this is probably the same with other versions – although I’m not sure about alternative implementations like GCJ) uses the following order to determine the canonical class name:

  1. Classes which are explicitly imported
  2. Classes which are in the current package
  3. Classes imported with wildcards

Just something to know about.

Picture taken from salimfadhley's photostream with permission.

PS. Amusing sidenote: when you search for import on Flickr, a lot of “babe” photos come up, even with safe search on. Is “import” a codeword for something? :-)

0 comments:

Post a Comment

You can use some HTML tags, such as <b>, <i>, <a>. Comments are moderated, so there will be a delay until the comment appears. However if you comment, I follow.