问题描述
我是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
子包中声明的类型。要回答这个问题,最好转向:
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:
换句话说,当你 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!