创建包
原文: https://docs.oracle.com/javase/tutorial/java/package/createpkgs.html
要创建包,请选择包的名称(命名约定将在下一节中讨论),并在顶部放置一个带有该名称的package
语句,每个包含类型的源文件(要包含在包中的类,接口,枚举和注释类型。
package 语句(例如,package graphics;
)必须是源文件中的第一行。每个源文件中只能有一个 package 语句,它适用于文件中的所有类型。
Note: If you put multiple types in a single source file, only one can be public
, and it must have the same name as the source file. For example, you can define public class Circle
in the file Circle.java
, define public interface Draggable
in the file Draggable.java
, define public enum Day
in the file Day.java
, and so forth.
You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private.
如果将上一节中列出的图形接口和类放在名为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
语句,则类型最终会出现在未命名的包中。一般来说,一个未命名的包只适用于小型或临时应用程序,或者刚刚开始开发过程。否则,类和接口属于命名包。