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?
There is no performance difference between a specific import and a wildcard import declaration. The information for the classes in imported package is not read in at compile time or run time unless the class is used in the program.
import * ) When an import statement in the pattern of from MODULE import * is used it may become difficult for a Python validator to detect undefined names in the program that imported the module.
No. Imports are purely a compile time construct ... syntactic sugar. The imports tell the Java compiler how to map identifiers in the source code to fully qualified class names.
Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names.
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event
, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event
. If you import both using the wildcard method, one of these three things happens:
java.awt.Event
and com.mycompany.calendar.Event
, and so you can't even compile..*
), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.com.mycompany.calendar.Event
, but when they later add one your previously valid code suddenly stops compiling.The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With