Java Programming/StarImports
From Wikibooks, the open-content textbooks collection
Many Java programmers avoid using the .* import syntax, e.g.,
import javax.swing.*;
There are a few reasons for this:
Contents |
[edit] Relevant Error Messages
If you import javax.swing.*; and then type JFraim frame=new JFraim();, the Java compiler will report 'cannot find symbol: JFraim' or similar. You'll think 'but I imported JFraim already'. The problem is that the compiler is giving the error report at the first mention of JFraim, which is half-way through your code, not at the point where you imported JFrame along with everything else in javax.swing.
If you change this to import javax.swing.JFraim; the error will be at the import, so the problem is more obvious.
In summary, the compiler error messages are more helpful if you use explicit imports. For beginners, this may prevent them having to seek help. For everybody else, it just speeds us up slightly.
[edit] Futureproofing
If you import javax.swing.*; and import java.util.*;, and some bright Sun engineer decides to add javax.swing.Queue in a future version of Java, your code that uses Queue (java.util) will fail to compile. This particular example is fairly unlikely, but if you are working with non-Sun libraries, it may be more likely to happen.
[edit] Readability
If you import everything from a few packages, it is difficult to see at a glance what types your code uses. You have to read all the code to work that out. The number of types imported (especially classes rather than interfaces) can be a good measure of coupling.
[edit] Understanding
New programmers who get accustomed to typing import javax.swing.*; etc. will often just look confused when they try to use something from outside the package[s] they imported, and often won't even identify which type comes from each package. For example, when using ActionListener, the new programmer may simply not realise that they need to import it from java.awt.event.
[edit] Yes, But I Use An IDE
Ok, yes, when you use an IDE that automatically manages imports, you don't need to worry so much about whether they're * or not. IDEs can help manage some of the above issues too.
[edit] I Am a Believer, But Don't Want To Type Lots
IDEs can normally add imports automatically, or with some user interaction, for code that you enter. They can be configured to not use .* imports, and they can normally 'organise imports', that is, adjust all your imports to be in alphabetical order and to replace .* imports with explicit imports, for a whole project at a time. For beginners, who shouldn't be using IDEs anyway, the code is probably not big enough that actually typing everything would take that long.

