在 Java 文件中定义包的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1088509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the purpose of defining a package in a Java file?
提问by derrdji
I am a newbie and just learned that if I define say
我是一个新手,刚刚了解到,如果我定义说
package my.first.group.here;
...
then the Java files that are in this package will be placed under my/first/group/here
directory.
那么这个包中的Java文件将被放置在my/first/group/here
目录下。
What is the main purpose of putting some Java files in a package? Also, if I choose to adopt this, how should I group them?
将一些 Java 文件放入包的主要目的是什么?另外,如果我选择采用这个,我应该如何将它们分组?
Thank you
谢谢
EDIT: For anyone who might have the same question again, I just found this tutorial on packagesfrom Sun.
采纳答案by William Brendel
Let's start with the definition of a "Java package", as described in the Wikipedia article:
让我们从“Java 包”的定义开始,如维基百科文章中所述:
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.
Java 包是一种将 Java 类组织到类似于 Modula 模块的命名空间中的机制。Java 包可以存储在称为 JAR 文件的压缩文件中,允许类作为一组而不是一次一个下载得更快。程序员通常还使用包来组织属于同一类别或提供类似功能的类。
So based on that, packages in Java are simply a mechanism used to organize classes and prevent class name collisions. You can name them anything you wish, but Sun has published some naming conventionsthat you shoulduse when naming packages:
因此基于此,Java 中的包只是一种用于组织类和防止类名冲突的机制。您可以随意命名它们,但 Sun 发布了一些命名约定,您应该在命名包时使用这些约定:
Packages
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.
Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
Examples:
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
套餐
唯一包名的前缀总是用全小写的ASCII字母书写,并且应该是顶级域名之一,目前是com、edu、gov、mil、net、org或英文双字母代码之一识别 ISO 标准 3166, 1981 中规定的国家/地区。
包名称的后续组成部分根据组织自己的内部命名约定而有所不同。此类约定可能指定某些目录名称组件是部门、部门、项目、机器或登录名。
例子:
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
回答by Paul Sonier
From the Wikipediapage on the topic:
从关于该主题的维基百科页面:
"A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality."
“Java 包是一种将 Java 类组织到类似于 Modula 模块的命名空间中的机制。Java 包可以存储在称为 JAR 文件的压缩文件中,从而允许类作为一组而不是一次下载更快。程序员通常也使用包来组织属于同一类别或提供类似功能的类。”
回答by Esko Luontola
It allows the program to be composed from multiple different programs/components/libraries, so that their class names will not conflict and the components are easier to organize. See http://java.sun.com/docs/books/tutorial/java/package/index.html
它允许程序由多个不同的程序/组件/库组成,这样它们的类名不会冲突,组件更容易组织。请参阅http://java.sun.com/docs/books/tutorial/java/package/index.html
In Java it's customary to name packages as reverse domain names. For example, if your company's domain is "initech.com" and you are making a program called "Gizmo", the package names are typically prefixed "com.initech.gizmo", with subpackages for different components of the program.
在 Java 中,习惯上将包命名为反向域名。例如,如果您公司的域是“initech.com”并且您正在制作一个名为“Gizmo”的程序,则包名称通常以“com.initech.gizmo”为前缀,并带有用于程序不同组件的子包。
回答by Mercer Traieste
Packages are important for giving flexibility of classes separation. They can be used for:
包对于提供类分离的灵活性很重要。它们可用于:
- separating projects
- separating modules
- separating application layers (business, web, dao)
- further finer grained code separation
- 分离项目
- 分离模块
- 分离应用层(业务、Web、DAO)
- 进一步细粒度的代码分离
For example
例如
com.mycompany.thisproject.thismodule.web
com.mycompany.thisproject.thismodule.web
Could indicate the web layer of some module.
可以指示某个模块的 web 层。
回答by geowa4
I a large application, you are bound to have two files named exactly the same (java.util.Date and java.sql.Date), especially when you start bringing in third party jars. So basically, you can use packages to ensure uniqueness.
我是一个大型应用程序,您肯定会有两个完全相同的文件(java.util.Date 和 java.sql.Date),尤其是当您开始引入第三方 jar 时。所以基本上,你可以使用包来确保唯一性。
Most importantly, in my opinion, packaging breaks down projects into meaningful segments. So my SQL package has sql-related code, and my logger package handles logging.
最重要的是,在我看来,打包将项目分解为有意义的部分。所以我的SQL包有sql相关的代码,我的logger包处理日志。
回答by Yohnny
also, if i choose to adopt this, how should i group them?
另外,如果我选择采用这个,我应该如何将它们分组?
This depends largely on the design pattern(s) you will employ in your project. For the most part (particularly, if you're quite new) you'll want to group them by functionality or some other logical similarity.
这在很大程度上取决于您将在项目中采用的设计模式。在大多数情况下(特别是如果您是新手),您会希望按功能或其他一些逻辑相似性对它们进行分组。
回答by Bill K
Java is very exact in its implementation. It doesn't really leave room for fudging.
Java 的实现非常精确。它并没有真正为捏造留下空间。
If everyone were to use the same package, they would have to find some "World Wide" way to ensure that no two class names ever collided.
如果每个人都使用同一个包,他们就必须找到某种“全球通用”的方式来确保两个类名不会发生冲突。
This lets every single class ever written fit into its own "Place" that you don't have to look at if you don't want to.
这让曾经编写的每个类都适合自己的“位置”,如果您不想,则不必查看。
You may have different "Point" objects defined in 4 different places on your system, but your class will only use the one you expect (because you import that one).
您可能在系统的 4 个不同位置定义了不同的“Point”对象,但是您的类将只使用您期望的对象(因为您导入了那个对象)。
The way they ensure that everyone has their own space is to use your reverse domain, so mine is "tv.kress.bill". I own that domain--Actually I share it with my brother "tv.kress.doug" and even though we share the same domain, we can't have a collision.
他们确保每个人都有自己的空间的方式是使用您的反向域,所以我的是“tv.kress.bill”。我拥有那个域——实际上我与我的兄弟“tv.kress.doug”共享它,即使我们共享同一个域,我们也不能发生冲突。
If a hundred divisions in your company each develop in Java, they can do so without collision and knowing exactly how to divide it.
如果您公司的一百个部门每个部门都使用 Java 开发,那么他们就可以在不发生冲突的情况下这样做,并且知道如何准确地划分它。
Systems that don't do this kind of division seem really flaky to me now. I might use them to hack together a script for something personal, but I'd feel uncomfortable developing anything big without some strict packaging going on.
不进行这种划分的系统现在对我来说似乎很不稳定。我可能会用它们来编写一些个人的脚本,但是如果没有一些严格的包装,我会觉得开发任何大的东西都不舒服。
回答by Bill K
Other people have provided very Java-specific answers which are fine, but here's an analogy: why do you organize files into directories on your hard drive? Why not just have a flat file system with everything in one directory?
其他人提供了非常特定于 Java 的答案,这很好,但这里有一个类比:为什么要将文件组织到硬盘驱动器上的目录中?为什么不只拥有一个将所有内容都放在一个目录中的平面文件系统?
The answer, of course, is that packages provide organization. The part of the program that interfaces with the database is different than the part of the program that displays a UI to the user, so they'll be in different packages.
答案当然是包提供了组织。与数据库交互的程序部分与向用户显示 UI 的程序部分不同,因此它们将位于不同的包中。
Like directories, it also provides a way to solve name conflicts. You can have a temp.txt in a couple different directories in the same way that you could have two classes that appear in different packages. This becomes important (1) when you start combining code with other people out there on the internet or (2) even realize how Java's classloading works.
与目录一样,它还提供了解决名称冲突的方法。您可以在几个不同的目录中拥有一个 temp.txt,就像您可以拥有两个出现在不同包中的类一样。当您开始将代码与 Internet 上的其他人组合在一起时,这变得很重要 (1) 或者 (2) 甚至意识到 Java 的类加载是如何工作的。
回答by Tamar
Another important thing about packages is the protectedmember for access control.
关于包的另一个重要事情是用于访问控制的受保护成员。
Protected is somewhere between public (everyone can access) and private (only class internal can access). Things marked as protected can be accessed from within the same package or from subclasses. This means that for limited access you don't have to put everything in the same class.
受保护介于公共(每个人都可以访问)和私有(只有内部类可以访问)之间。标记为 protected 的东西可以从同一个包或子类中访问。这意味着对于有限的访问,您不必将所有内容都放在同一个类中。
回答by Rich Seller
In addition to the namespacing mentioned in other answers, you can limit access to methods and fields based on the scope declared on that member. Members with the publicscope are freely accessible, to limit access you normally define them as private(i.e. hidden outside the class). You can also use the protectedscope to limit access to the type and its children. There is also the defaultscope (a member with no qualifier has the default scope) which allows child types and types in the same package access to the member. This can be an effective way of sharing fields and methods without making them too widely available, and can help with testing.
除了其他答案中提到的命名空间之外,您还可以根据在该成员上声明的范围来限制对方法和字段的访问。具有公共范围的成员可以自由访问,为了限制访问,您通常将它们定义为私有(即隐藏在类之外)。您还可以使用受保护的范围来限制对类型及其子项的访问。还有默认范围(没有限定符的成员具有默认范围),它允许子类型和同一包中的类型访问该成员。这可以是一种共享字段和方法的有效方式,而不会使其过于广泛可用,并且可以帮助进行测试。
For example the method below would be visible to all other members of the same package.
例如,下面的方法将对同一包的所有其他成员可见。
public class Foo {
int doSomething() {
return 1;
}
}
To test the method you could define another type in the same package (but probably a different source location), that type would be able to access the method.
要测试该方法,您可以在同一个包中定义另一种类型(但可能是不同的源位置),该类型将能够访问该方法。
public class FooTest {
@Test
int testDoSomething() {
Foo foo = new Foo();
assertEquals(1, foo.doSomething());
}
}