递归导入Java [英] Recursive import Java
问题描述
我是Java开发的新手。我有一个关于Java中递归导入的快速问题。
I am a newbie to Java development. I have a quick question regarding recursive imports in Java.
让我们假设包pkg包含以下内容
Lets assume Package "pkg" contains the following
- A类,
- 包B(这又包含B1类)
- 包C(这又包含C1 class)
如果我使用 import pkg。*
为什么我不被允许从包B和C导入类??
If I use import pkg.*
why am I not allowed to import classes from packages "B" and "C" ?.
我想了解Java中不允许我进行递归导入的理由。
I would like to understand the rationale behind in Java's not allowing me to do recursive imports.
推荐答案
你的问题措辞不当,因为如果你导入pkg。*
,你当然可以从包 pkg.B
和 pkg.C
中导入类。也就是说,这样做非常好:
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.*;
但我认为你真正要问的是为什么,如果你 import pkg。*
它不会自动导入 pkg
子包中声明的类型。要回答这个问题,最好转向 Java语言规范:
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:
包的分层命名结构旨在方便以传统方式组织相关包,但除了禁止具有与该包中声明的顶级类型(第7.6节)相同的简单名称的子包之外,本身没有任何意义。
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.
例如,名为 oliver
的包与另一个名为 oliver.twist
,或名为 evelyn.wood
和 evelyn.waugh
的包之间。也就是说,名为 oliver.twist
的包中的代码无法更好地访问包 oliver
中声明的类型。任何其他包中的代码。
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.
换句话说,当你 import pkg。*
,您要导入由名为 pkg
的包中包含的编译单元定义的所有顶级类型,但是您是不导入 pkg
的任何子包(例如 pkg.B
或 pkg.C
)。
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
).
这篇关于递归导入Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!