Inheritance Basics

Java supports inheritance by allowing one class to incorporate another class into its declaration. This is done by using the extends keyword. Thus, the subclass adds to (extends) the superclass.

Let’s begin with a short example that illustrates several of the key features of inheritance. The following program creates a superclass called TwoDShape, which stores the width and height of a two-dimensional object, and a subclass called Triangle. Notice how the keyword extends is used to create a subclass.

Image

Image

Here, TwoDShape defines ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.