Subclassing and Inheritance
Most object-oriented programming languages, including Ruby, provide a subclassing mechanism that allows us to create new classes whose behavior is based on, but modified from, the behavior of an existing class. We’ll begin this discussion of subclassing with definitions of basic terminology. If you’ve programmed in Java, C++, or a similar language, you are probably already familiar with these terms.
When we define a class, we may specify that it
extends—or inherits
from—another class, known as the
superclass. If we define a class Ruby that extends a class Gem, we say that Ruby is a subclass
of Gem, and that
Gem is the
superclass of Ruby. If you do not specify a superclass when
you define a class, then your class implicitly extends Object. A class may have any number of
subclasses, and every class has a single superclass except Object, which has none.
The fact that classes may have multiple subclasses but only a
single superclass means that they can be arranged in a tree structure,
which we call the Ruby class hierarchy. The Object class is the root of this hierarchy,
and every class inherits directly or indirectly from it. The descendants of a class are the
subclasses of the class plus the subclasses of the subclasses, and so on
recursively. The ancestors of a class are the superclass, plus the superclass of the
superclass, and so on up to Object.
Figure 5-5 in Chapter 5
illustrates the portion of the Ruby class hierarchy that includes
Exception and all ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access