- In a hierarchy, each class has at most one superclass, but might have several subclasses. There is one class, at the top of the hierarchy that has no superclass. This is sometimes called the root of the hierarchy.
Figure 11.3 - Person
Inheritance Hierarchy
Figure 11.3 shows a hierarchy of classes. It shows that a Principal
is a Person
, a Student
is a Person
, and that a Teacher
is a Person
. It also shows that both HighSchoolStudent
and CollegeStudent
are types of Student
.
In our example, the class Person
is the base class and the classes Principal, Student, Teacher, HighSchoolStudent
, and CollegeStudent
are derived classes.
In Java, the syntax for deriving a child class from a parent class is:
Several classes are often subclasses of the same class. A subclass may in turn become a parent class for a new subclass. This means that inheritance can extend over several "generations" of classes. This is shown in Figure 11.3, where class HighSchoolStudent
is a subclass of class Student
, which is itself a subclass of the Person
class. In this case, class HighSchoolStudent
is considered to be a subclass of the Person
class, even though it is not a direct subclass.
- In Java, every class that does not specifically extend another class is a subclass of the class
Object
. For example, in Figure 11.3, the Person
class extends the class Object
. The class Object
has a small number of methods that make sense for all objects, such as the toString
method, but the class Object
’s implementations of these methods are not very useful and the implementations usually get redefined in classes lower in the hierarchy.