Documentation

The Java™ Tutorials
Hide TOC
Creating and Using Packages创建和使用包
Trail: Learning the Java Language
Lesson: Packages

Creating and Using Packages创建和使用包

To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.为了使类型更易于查找和使用,避免命名冲突,并控制访问,程序员将相关类型的组捆绑到包中。


Definition:定义: A package is a grouping of related types providing access protection and name space management. 是一组提供访问保护和名称空间管理的相关类型。Note that types refers to classes, interfaces, enumerations, and annotation types. 请注意,类型指的是类、接口、枚举和注释类型。Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. 枚举和注释类型分别是特殊类型的类和接口,因此在本课程中,类型通常被称为类和接口

The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. 作为Java平台一部分的类型是按函数捆绑类的各种包的成员:基本类在Java.lang中,用于读写(输入和输出)的类在Java.io中,等等。You can put your types in packages too.您也可以将类型放入包中。

Suppose you write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. 假设您编写了一组表示图形对象的类,例如圆、矩形、直线和点。You also write an interface, Draggable, that classes implement if they can be dragged with the mouse.您还编写了一个接口Dragable,如果可以用鼠标拖动类,则类将实现该接口。

//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 {
    . . .
}

You should bundle these classes and the interface in a package for several reasons, including the following:出于以下几个原因,您应该将这些类和接口捆绑在一个包中:


Previous page: Packages
Next page: Creating a Package