Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
为了使类型更易于查找和使用,避免命名冲突,以及控制访问,程序员将相关类型的组组织到包中。
作为 Java 平台一部分的类型是按功能组织类的各种包的成员:基本类在 java.lang 中,用于读写(输入和输出)的类在 java.io 中等等。你也可以将你的类型放入包中。
假设你编写了一组表示图形对象的类,例如圆形,矩形,线和点。你还可以编写一个接口 Draggable,如果可以使用鼠标拖动它们,那么这些类就可实现该接口。
//in the Draggable.java file
public interface Draggable {
...
}
//in the Graphic.java file
public abstract class Graphic {
...
}
//in the Circle.java file
public class Circle extends Graphic
implements Draggable {
. . .
}
//in the Rectangle.java file
public class Rectangle extends Graphic
implements Draggable {
. . .
}
//in the Point.java file
public class Point extends Graphic
implements Draggable {
. . .
}
//in the Line.java file
public class Line extends Graphic
implements Draggable {
. . .
}
你应该将这些类和接口组织在一个包中,原因有多种,包括: