Subclassing and Inheritance
Classes in Java exist in a hierarchy. A class in Java can be
declared as a subclass of another class using the
extends keyword. A
subclass inherits variables and methods from its
superclass and can use them as if they were declared
within the subclass itself:
classAnimal{floatweight;...voideat(){...}...}classMammalextendsAnimal{// inherits weightintheartRate;...// inherits eat()voidbreathe(){...}}
In this example, an object of type Mammal has both the instance variable weight and the method eat(). They are inherited from Animal.
A class can extend only one other class. To use the proper terminology, Java allows single inheritance of class implementation. Later in this chapter, we’ll talk about interfaces, which take the place of multiple inheritance as it’s primarily used in other languages.
A subclass can be further subclassed. Normally, subclassing specializes or refines a class by adding variables and methods (you cannot remove or hide variables or methods by subclassing). For example:
classCatextendsMammal{// inherits weight and heartRatebooleanlongHair;...// inherits eat() and breathe()voidpurr(){...}}
The Cat class is a type of
Mammal that is ultimately a type of
Animal. Cat objects inherit all the characteristics of
Mammal objects and, in turn, Animal objects. Cat also provides additional behavior in the
form of the purr() method and the
longHair variable. We can denote the class relationship in a diagram, ...