It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import
statement?
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see
import ...*
.C# always uses * (implicitly) as you can only
using
package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
The most important one is that importing
java.awt.*
can make your program incompatible with a future Java version:Suppose that you have a class named "ABC", you're using JDK 8 and you import
java.util.*
. Now, suppose that Java 9 comes out, and it has a new class in packagejava.util
that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class injava.awt
.You won't have that problem when you import only those classes explicitly from
java.awt
that you actually use.Resources:
Java Imports
In DDD book
And if it clutters local namespace its not your fault - blame the size of the package.