gpt4 book ai didi

java - Java 包是嵌套的还是非嵌套的……两者都是?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:38 24 4
gpt4 key购买 nike

我对在 Java 中导入包感到困惑。

当我需要import java.util.Scanner 时,它也是通过这样的导入语句完成的:import java.util.*(这对我,因为 Scanner 类在 util 中)。

但是这个技巧适用于 java.awt.eventjava.awt.* 。这让我更加困惑。 (如果您的回答是 Java 包不是嵌套的,请告诉我上述技巧起作用的原因。如果 Java 既有嵌套包又有独立包,我该如何找到它们?

最佳答案

导入通配符不是递归的。

导入 java.awt.* NOTjava.awt.event 导入任何内容。它只导入 java.awt 中的类,而不是它的“子包”。

还应该注意的是,导入包实际上任何事情,它只是告诉 Java 去哪里寻找您使用的类名。

此外,无论如何使用通配符有点草率。您可能应该只导入您实际使用的类。

编辑:这个问题之前被问过:Recursive import Java在谷歌上快速搜索“java 递归导入包”会得到一大堆结果,包括:

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

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

关于java - Java 包是嵌套的还是非嵌套的……两者都是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com