Documentation

The Java™ Tutorials
Hide TOC
Declaring Classes声明类
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: Classes

Declaring Classes声明类

You've seen classes defined in the following way:您已经看到了以以下方式定义的类:

class MyClass {
    // field, constructor, and 
    // method declarations
}

This is a class declaration.这是一个类声明The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.类主体(大括号之间的区域)包含为从类创建的对象的生命周期提供的所有代码:初始化新对象的构造函数、提供类及其对象状态的字段声明,以及实现类及其对象行为的方法。

The preceding class declaration is a minimal one.前面的类声明是最小的声明。It contains only those components of a class declaration that are required.它只包含类声明中需要的组件。You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration.您可以在类声明的开头提供有关该类的更多信息,例如其超类的名称、它是否实现了任何接口等。For example,例如

class MyClass extends MySuperClass implements YourInterface {
    // field, constructor, and
    // method declarations
}

means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.意味着MyClassMySuperClass的一个子类,它实现了YourInterface接口。

You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated.您还可以在开始时添加诸如publicprivate之类的修饰符—因此,您可以看到类声明的开头行可能变得非常复杂。The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson.修饰符publicprivate决定哪些其他类可以访问MyClass,将在本课后面讨论。The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration.关于接口和继承的课程将解释如何以及为什么在类声明中使用extendsimplements关键字。For the moment you do not need to worry about these extra complications.目前,你不必担心这些额外的并发症。

In general, class declarations can include these components, in order:通常,类声明可以包括以下组件:

  1. Modifiers such as public, private, and a number of others that you will encounter later.修饰符,例如publicprivate以及稍后将遇到的其他一些修饰符。(However, note that the private modifier can only be applied to Nested Classes.)(但是,请注意,private修饰符只能应用于嵌套类。)
  2. The class name, with the initial letter capitalized by convention.类名,首字母按约定大写。
  3. The name of the class's parent (superclass), if any, preceded by the keyword extends.类的父类(超类)的名称(如果有),前面加上关键字extendsA class can only extend (subclass) one parent.一个类(子类)只能扩展一个父类。
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements.由类(如果有)实现的接口的逗号分隔列表,前面有关键字implementsA class can implement more than one interface.一个类可以实现多个接口。
  5. The class body, surrounded by braces, {}.类主体,由大括号{}包围。

Previous page: Classes
Next page: Declaring Member Variables