创建包

原文: 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的包中,则需要六个源文件,如下所示:

  1. //in the Draggable.java file
  2. package graphics;
  3. public interface Draggable {
  4. . . .
  5. }
  6. //in the Graphic.java file
  7. package graphics;
  8. public abstract class Graphic {
  9. . . .
  10. }
  11. //in the Circle.java file
  12. package graphics;
  13. public class Circle extends Graphic
  14. implements Draggable {
  15. . . .
  16. }
  17. //in the Rectangle.java file
  18. package graphics;
  19. public class Rectangle extends Graphic
  20. implements Draggable {
  21. . . .
  22. }
  23. //in the Point.java file
  24. package graphics;
  25. public class Point extends Graphic
  26. implements Draggable {
  27. . . .
  28. }
  29. //in the Line.java file
  30. package graphics;
  31. public class Line extends Graphic
  32. implements Draggable {
  33. . . .
  34. }

如果不使用package语句,则类型最终会出现在未命名的包中。一般来说,一个未命名的包只适用于小型或临时应用程序,或者刚刚开始开发过程。否则,类和接口属于命名包。