Vignesh Vignesh - 7 months ago 21
Java Question

Are Java packages nested, not nested... both?

I'm confused about importing packages in Java.

When I need to

import java.util.Scanner
, it is also done by the import statement like this:
import java.util.*
(this makes sense to me, as the
Scanner
class is in inside
util
).

But this trick works for
java.awt.event
and
java.awt.*
. This makes me more confused. (If your answer is that Java packages are not nested, please tell me the reason why the above tricks works. And if Java has both nested and independent packages how i can find them?

Answer

Import wildcards are not recursive.

Importing java.awt.* does NOT import anything from java.awt.event. It only imports the classes in java.awt, not its "subpackages".

It should also be noted that importing a package doesn't actually do anything, it simply tells Java where to look for the class names you use.

Also, using wildcards is a bit sloppy anyway. You should probably be importing only the classes you actually use.

Edit: This question has been asked before: Recursive import Java and a quick google search of "java recursive import package" turns up a whole bunch of results, including:

The Java tutorials:

At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files:

import java.awt.*; import java.awt.color.*;

And the JLS:

The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in itself other than the prohibition against a package having a subpackage with the same simple name as a top level type (ยง7.6) declared in that package.

For example, there is no special access relationship between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.waugh. That is, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.

Comments