Question

I have a logical question: Why i cannot import all packages from all packages in java? For example i can import all classes from java.awt:

import java.awt.*;

But the following isnt possible:

import java.awt.*.*;

My aim would be to import all stuff from awt.image and awt.event and so on. Is there another way to do this?

Thank you!

Was it helpful?

Solution

There is no way to achieve an import a.package.*.*; in Java. The JLS, Section 7.5 specifies the only 4 types of imports that are legal:

A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).

e.g. import java.util.List;

A type-import-on-demand declaration (§7.5.2) imports all the accessible types (§6.6) of a named type or named package as needed, by mentioning the canonical name of a type or package.

e.g. import java.awt.*;

A single-static-import declaration (§7.5.3) imports all accessible static members with a given name from a type, by giving its canonical name.

e.g. import static org.junit.Assert.assertEquals;

A static-import-on-demand declaration (§7.5.4) imports all accessible static members of a named type as needed, by mentioning the canonical name of a type.

e.g. import static org.junit.Assert.*;

Packages allow classes of the same name to be referenced individually. E.g. there is java.awt.List and java.util.List. What would stop someone from importing everything with java.*.*;. How would List be resolved then? There would be too much ambiguity.

OTHER TIPS

No, and using wildcard imports is bad style in general as it makes your code harder to read.

Some disadvantages of using wildcards imports:

  1. Results in including classes that you might not use at all. Not clear picture of what you are working with.
  2. More broader scope which is considered bad programming practice.
  3. Most important can result in namespace clash. If you are blatantly importing everything from two packages it may result in clash between two classes with same name from different packages.

Edit: Seems like importing more classes than required doesn't result in any bulky code, but I would still prefer to import the classes explicitly to have a clear idea about what I am working with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top