Documentation

The Java™ Tutorials
Hide TOC
Naming a Package命名包
Trail: Learning the Java Language
Lesson: Packages
Section: Creating and Using Packages

Naming a Package命名包

With programmers worldwide writing classes and interfaces using the Java programming language, it is likely that many programmers will use the same name for different types. 由于世界各地的程序员都使用Java编程语言编写类和接口,许多程序员可能会对不同的类型使用相同的名称。In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. 事实上,前面的示例就是这样做的:当java.awt包中已经有一个Rectangle类时,它定义了一个Rectangle类。Still, the compiler allows both classes to have the same name if they are in different packages. 尽管如此,如果两个类位于不同的包中,编译器仍然允许它们具有相同的名称。The fully qualified name of each Rectangle class includes the package name. 每个Rectangle类的完全限定名包括包名。That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.也就是说,graphics包中Rectangle类的完全限定名为graphics.Rectanglejava.awt包中矩形类的完全限定名为java.awt.Rectangle

This works well unless two independent programmers use the same name for their packages. 除非两个独立的程序员对他们的包使用相同的名称,否则这种方法很有效。What prevents this problem? Convention.是什么防止了这个问题?约定。

Naming Conventions命名约定

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.包名以小写形式编写,以避免与类或接口的名称冲突。

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.公司使用其反向互联网域名作为其软件包名称的开头—例如,com.example.mypackage用于由程序员在example.com创建的名为mypackage的包。

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).单个公司内发生的名称冲突需要按照该公司内的约定进行处理,可能需要在公司名称(例如,com.example.region.mypackage)后包含区域或项目名称。

Packages in the Java language itself begin with java. or javax.Java语言本身中的包以java.或者javax.开头。

In some cases, the internet domain name may not be a valid package name. 在某些情况下,internet域名可能不是有效的包名。This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". 如果域名包含连字符或其他特殊字符,如果包名以数字或其他非法用作Java名称开头的字符开头,或者包名包含保留的Java关键字(如“int”),则可能发生这种情况。In this event, the suggested convention is to add an underscore. 在这种情况下,建议的约定是添加下划线。For example:例如:

Legalizing Package Names使包名合法化
Domain Name域名 Package Name Prefix包名称前缀
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name

Previous page: Creating a Package
Next page: Using Package Members