Cover by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required