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 the class body of the base class, so any methods or fields that are defined by the base class will automatically be included in the subclass. Thus, the class body for a subclass includes only the methods or fields that differentiate the subclass from its base class.
For example, suppose you have a class named Ball
that defines a basic ball, and you want to create a subclass named BouncingBall
that adds the ability to bounce. You could do that like this:
public class BouncingBall extends Ball
{
public void bounce()
{
// the bounce method
}
}
Here are some other important details about creating subclasses:
The visibility (public
or private
) of any members inherited from the base class is the same in the subclass. That means that you can’t access from the subclass methods or fields that are declared in the base class as private
.
You can override a method by declaring a new member with the same signature in the subclass. For more information, see Inner Class.
A special type of visibility called protected
hides fields and methods from other classes but makes them available to subclasses. For more information, see private Keyword.
You can add more methods or fields — private
, public
, or protected
— to a subclass. The Bouncing Ball
class shown earlier in this section, for example, adds a public method named bounce
.