Inheritance

Inheritance refers to a feature of Java programming that lets you create classes that are derived from other classes. A class that’s based on another class inherits the other class. The class that is inherited is the parent class, the base class, or the superclass. The class that does the inheriting is the child class, the derived class, or the subclass.

A subclass automatically takes on all the behavior and attributes of its base class. Thus, if you need to create several classes to describe types that aren’t identical but have many features in common, you can create a base class that defines all the common features. Then you can create subclasses that inherit the common features.

A subclass can add features to the base class it inherits by defining its own methods and fields. This is one of the ways a derived class distinguishes itself from its base class.

A subclass can also change the behavior provided by the base class. A base class may provide that all classes derived from it have a method named play, for example, but each class is free to provide its own implementation of the play method. In this case, all classes that extend the base class provide their own implementation of the play method.

To create a subclass, you use the extends keyword on the class declaration to indicate the name of the base class. The basic format of a subclass declaration is this:

public class ClassName extends BaseClass

{

// class body goes here

}

The subclass automatically inherits ...

Get Java For Dummies Quick Reference 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.