Thursday, January 25, 2007

Java fully qualified import

In Java, one can import all the classes in package using "import a.b.c*" form of import statement. It is also possible to import classes individually using "import a.b.c.ClassName" form of import statement.

Typically, the latter method is preferred, since it improves readability: in order to determine the package that a class belongs to, the reader just needs to look at the import statements at the top of the file.

However there is another important reason to always choose latter method. Let's say you use import a.b.* form to import all classes from packages X and Y, and package Y contains class Z that is used by your class. Time passes, and class with name Z is added to package X as well. Suddenly, your class doesn't compile because the compiler is unable to determine which package class Z comes from.

Thus, it is always preferable to import every class individually rather than all classes in a package.

No comments: