Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Object-Oriented Programming Concepts
What Is an Object?
What Is a Class?
What Is Inheritance?
What Is an Interface?
What Is a Package?
Questions and Exercises
Trail: Learning the Java Language
Lesson: Object-Oriented Programming Concepts
Home Page >Learning the Java Language >Object-Oriented Programming Concepts
« Previous • Trail • Next »

The Java Tutorials have been written for 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.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

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 toinherit commonly used state and behavior from other classes. In this example,Bicycle now becomes thesuperclass ofMountainBike,RoadBike, andTandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number ofsubclasses:

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 theextends keyword, followed by the name of the class to inherit from:

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

This givesMountainBike all the same fields and methods asBicycle, yet allows its code to focus exclusively on the features that make it unique. 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.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

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

[8]ページ先頭

©2009-2025 Movatter.jp