Documentation

The Java™ Tutorials
Hide TOC
What Is Inheritance?什么是继承?
Trail: Learning the Java Language
Lesson: Object-Oriented Programming Concepts

What Is Inheritance?什么是继承?

Different kinds of objects often have a certain amount in common with each other.不同种类的物体往往有一定数量的共同点。Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear).例如,山地自行车、公路自行车和双人自行车都具有自行车的特征(当前速度、当前踏板节奏、当前档位)。Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.然而,每辆车都定义了使其与众不同的附加功能:双人自行车有两个座位和两套把手;公路自行车有下降把手;一些山地自行车有一个额外的链条环,使他们有一个较低的齿轮比。

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.面向对象编程允许类从其他类继承常用的状态和行为。In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike.在本例中,Bicycle现在成为MountainBikeRoadBikeTandemBike的超类。In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:在Java编程语言中,每个类都允许有一个直接超类,每个超类都有无限数量的子类

A diagram of classes in a hierarchy.

A hierarchy of bicycle classes.自行车类的层次结构。

The syntax for creating a subclass is simple.创建子类的语法很简单。At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:在类声明的开头,使用extends关键字,后跟要从中继承的类的名称:

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique.这给了MountainBike所有与Bicycle相同的字段和方法,但允许其代码专门关注使其独特的功能。This makes code for your subclasses easy to read.这使得子类的代码易于阅读。However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.但是,您必须注意正确地记录每个超类定义的状态和行为,因为这些代码不会出现在每个子类的源文件中。


Previous page: What Is a Class?
Next page: What Is an Interface?