I am a newbie to Java development. I have a quick question regarding recursive imports in Java.
Lets assume Package "pkg" contains the following
If I use import pkg.*
why am I not allowed to import classes from packages "B" and "C" ?.
I would like to understand the rationale behind in Java's not allowing me to do recursive imports.
Your question is poorly phrased, because if you import pkg.*
, you certainly are allowed to then import classes from packages pkg.B
and pkg.C
. That is, it is perfectly fine to do this:
import pkg.*;
import pkg.B.*;
import pkg.C.*;
But I assume that what you really are asking is why, if you import pkg.*
it does not automatically import the types declared in the subpackages of pkg
. To answer that, it's best to turn to the Java Language Specification:
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 namedoliver.twist
, or between packages namedevelyn.wood
andevelyn.waugh
. That is, the code in a package namedoliver.twist
has no better access to the types declared within packageoliver
than code in any other package.
In other words, when you import pkg.*
, you are importing all the top-level types defined by the compilation units contained in the package named pkg
, but you are not importing any of the sub-packages of pkg
(such as pkg.B
or pkg.C
).
It sounds like you're asking why import java.awt.*
doesn't also import java.awt.color.*
and so on.
This is best explained by this tutorial where it says
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.
More importantly,
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.*;
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