Java教程
  • Introduction
  • Getting Started
    • The Java Technology Phenomenon
      • About the Java Technology
      • What Can Java Technology Do?
      • How Will Java Technology Change My Life?
    • The Hello World Application
    • A Closer Look at the Hello World Application
  • Learning the Java Language
    • Object-Oriented Programming Concepts
      • What Is an Object?
      • What Is a Class?
      • What Is Inheritance?
      • What Is an Interface?
      • What Is a package?
    • Language Basics
      • Java Language Keywords
    • Annotations
      • Annotations Basics
      • Declaring an Annotation Type
      • Predefined Annotation Types
      • Repeating Annotations
      • Type Annotations and Pluggable Type Systems
    • Generics
      • Why Use Generics?
      • Generic Types
        • Raw Types
      • Generic Methods
      • Bounded Type Parameters
        • Generic Methods and Bounded Type Parameters
      • Generics, Inheritance, and Subtypes
      • Type Inference
      • Wildcards
        • Upper Bounded Wildcards
        • Unbounded Wildcards
        • Lower Bounded Wildcards
        • Wildcards and Subtyping
        • Wildcard Capture and Helper Methods
        • Guidelines for Wildcard Use
      • Type Erasure
        • Erasure of Generic Types
        • Erasure of Generic Methods
        • Effects of Type Erasure and Bridge Methods
        • Non-Reifiable Types
      • Restrictions on Generics
Powered by GitBook
On this page

Was this helpful?

  1. Learning the Java Language
  2. Object-Oriented Programming Concepts

What Is Inheritance?

PreviousWhat Is a Class?NextWhat Is an Interface?

Last updated 5 years ago

Was this helpful?

不同类型的对象之间经常会有某些相同的地方。比如,山地自行车,公路自行车和双人自行车都具有自行车的特征(当前速度、当前踏板节奏、当前档位)。然而它们同样定义了使它们不同的附加特性:双人自行车有两个座位和两幅车把;公路自行车有赛车车把;有些山地有一个额外的连环,使得它们有更低的档位比。

面向对象编程允许类从其他类inherit(继承)通用的状态和行为。在这个例子中,Bicycle是MountainBike,RoadBike和TandemBike的superclass(超类)。在Java编程语言中每个类可以有一个直接超类,每个超类可能有无限数量的subclass子类:

A hierarchy of bicycle classes

创建子类的语法很简单。在你类定义的前端使用extends关键字,后面紧跟着被继承类的名字:


class MountainBike extends Bicycle {
// new fields and methods defining
// a mountain bike would go here
}

这让MountainBike拥有Bicycle一样的属性和函数,但允许其代码只关注使其独特的特性。这使得你的子类的代码更易于阅读。但是,你必须注意正确地为每个超类定义的状态和行为提供文档,因为超类代码不会出现在每个子类的源文件中。