为什么让 2 个编译单元具有相同的包名是有意义的?
Why does it makes sense to have 2 compilation units the same package name?
我正在阅读 Bruce Eckel 的Thinking in Java,第 4 版,他介绍了包的概念以及它们如何更好地遵循 [=24= 的层次结构] 以便于访问和整理 class 个文件。
嗯,他说,
Each compilation unit must have a name ending in .java, and inside the
compilation unit there can be a public class that must have the same
name as the file (including capitalization, but excluding the .java
file name extension). There can be only one public class in each
compilation unit; otherwise, the compiler will complain.
现在,可以有多个编译单元具有相同的包名(我测试过)。但为什么以这种方式拥有它是有意义的呢?这样它们就不会彼此 绝缘 并且当你编译它们时,所有 class 文件都在 1 个目录中。
For a compilation unit, there is a main class and support classes. But if 2 compilation units have the same package name, and you compile manually using javac commandline, all the classes will end up in the same directory but not all are logically associated with each other. So, why does it make sense for 2 compilation units to have the same package name?
当你拥有彼此相关的代码库(一组class)时,只有你将它们放在同一个包中。否则总是为 classes 提供不同的包,它们提供不同的功能。
如果您指定相同的包名称并编译它们,它们将最终位于同一目录中,因为您就是这样定义它们的。 Java 编译器不会检查所有具有相同包名的 class 是否相关。这是程序员的选择,他想把什么class放在同一个包里,什么class放在不同的包里。
你可以拿java JDK代码举例。所有与输入和输出相关的 classes 都放在 io
包中,实用程序 classes 放在 util
包中,等等
据我了解,当您从事大型项目时,如何命名每个 class 和 非常重要如何在包层次结构中进一步组织它们。
希望它能清除一些空气。
我正在阅读 Bruce Eckel 的Thinking in Java,第 4 版,他介绍了包的概念以及它们如何更好地遵循 [=24= 的层次结构] 以便于访问和整理 class 个文件。
嗯,他说,
Each compilation unit must have a name ending in .java, and inside the compilation unit there can be a public class that must have the same name as the file (including capitalization, but excluding the .java file name extension). There can be only one public class in each compilation unit; otherwise, the compiler will complain.
现在,可以有多个编译单元具有相同的包名(我测试过)。但为什么以这种方式拥有它是有意义的呢?这样它们就不会彼此 绝缘 并且当你编译它们时,所有 class 文件都在 1 个目录中。
For a compilation unit, there is a main class and support classes. But if 2 compilation units have the same package name, and you compile manually using javac commandline, all the classes will end up in the same directory but not all are logically associated with each other. So, why does it make sense for 2 compilation units to have the same package name?
当你拥有彼此相关的代码库(一组class)时,只有你将它们放在同一个包中。否则总是为 classes 提供不同的包,它们提供不同的功能。
如果您指定相同的包名称并编译它们,它们将最终位于同一目录中,因为您就是这样定义它们的。 Java 编译器不会检查所有具有相同包名的 class 是否相关。这是程序员的选择,他想把什么class放在同一个包里,什么class放在不同的包里。
你可以拿java JDK代码举例。所有与输入和输出相关的 classes 都放在 io
包中,实用程序 classes 放在 util
包中,等等
据我了解,当您从事大型项目时,如何命名每个 class 和 非常重要如何在包层次结构中进一步组织它们。
希望它能清除一些空气。