Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
要创建包,请选择包的名称(命名规范将在下一节中讨论),并将带有该名称的 package 语句放在 每一个源码文件 的顶部,源文件包含要包含在包中的类型(类,接口,枚举和注解类型)。
package 语句(例如,package graphics;)必须是源文件中的第一行。每个源文件中只能有一个 package 语句,它适用于文件中的所有类型。
public,并且它必须与源文件具有相同的名称。例如,你可以在文件 Circle.java 中定义 public class Circle,在文件 Draggable.java 中定义 public interface Draggable ,在文件 Day.java 中定义 public enum Day等等。如果将上一节中列出的图形接口和类放在名为 graphics 的包中,则需要六个源文件,如下所示:
//in the Draggable.java file
package graphics;
public interface Draggable {
. . .
}
//in the Graphic.java file
package graphics;
public abstract class Graphic {
. . .
}
//in the Circle.java file
package graphics;
public class Circle extends Graphic
implements Draggable {
. . .
}
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic
implements Draggable {
. . .
}
//in the Point.java file
package graphics;
public class Point extends Graphic
implements Draggable {
. . .
}
//in the Line.java file
package graphics;
public class Line extends Graphic
implements Draggable {
. . .
}
如果不使用 package 语句,则类型最终会出现在未命名的包中。一般来说,一个未命名的包只适用于小型或临时应用程序,或者刚刚开始开发过程。否则,类和接口属于命名的包。