Recursive import Java

后端 未结 4 1175
無奈伤痛
無奈伤痛 2021-01-18 18:24

I am a newbie to Java development. I have a quick question regarding recursive imports in Java.

Lets assume Package \"pkg\" contains the following

  • clas
4条回答
  •  一向
    一向 (楼主)
    2021-01-18 18:59

    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 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.

    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).

提交回复
热议问题