The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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
现在成为MountainBike
、RoadBike
和TandemBike
的超类。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 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.但是,您必须注意正确地记录每个超类定义的状态和行为,因为这些代码不会出现在每个子类的源文件中。