liveBook · Manning

Superclass

As explained in The Well-Grounded Rubyist, Fourth Edition

A superclass is the class from which another Ruby class inherits methods and other behavior.

Suppose a magazine needs everything a publication has, plus an editor. Define Magazine as a subclass of Publication with `<`. Publication is its superclass; Magazine instances can use Publication’s instance methods as well as their own. section 3.5

class Publication
  attr_accessor :publisher
end
class Magazine < Publication
  attr_accessor :editor
end

The inherited `publisher` accessor works on a Magazine instance even though only `editor` is declared in Magazine. section 3.5

The chain can continue: `class Ezine < Magazine; end` gives Ezine instances access to methods defined in both Magazine and Publication. A subclass need not add methods; its name alone may make code more expressive. To inspect the chain, call `superclass` on a class: if `D < C` and C declares no superclass, `D.superclass` is C and `D.superclass.superclass` is Object. section 3.5 section 3.5.2

A superclass is part of method lookup, not a permanent inventory of everything an object can do. Lookup can pass through a class, included modules, and ancestral classes. An individual object can also gain a singleton method, and adding an instance method to an ancestral class can change an existing object’s capabilities. section 4.2.1 section 3.8

Choose a superclass with two constraints in mind:

  • Ruby classes have only one superclass. Modules can supply additional shared methods without occupying that relationship. section 3.5.1 section 4.4.1
  • An “is a” relationship can make a hierarchy clear—an Ezine is a Magazine—but inheritance also serves to share behavior. Prefer a sensible superclass over one chosen merely for a set of characteristics. section 3.8 section 4.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through subclass syntax, inherited behavior, ancestry inspection, and design limits; extends method lookup to modules without detailing its full implementation.
Examples
Demonstrates Publication–Magazine–Ezine inheritance, `D.superclass` inspection, and an inherited module method.
What it assumes
Assumes familiarity with classes, instances, and methods while explaining inherited accessors and ancestry through small examples.
What you can do after
Build it from scratch by declaring a subclass with `<`, checking its ancestry, and choosing modules when inheritance is unsuitable.
How it connects
Connects superclasses to subclasses, instance methods, method lookup, modules, singleton methods, Object, and BasicObject.

Also explained in

Compare how 10 books explain superclass →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.