RUBY / CHAPTER 10
Inheritance, super, and substitution
AdvancedExtend behavior while respecting the parent’s promises.
By the end of this chapter
- Trace overridden method calls
- Use super with intentional arguments
- Choose composition for has-a relationships
The idea
A subclass can inherit behavior and override selected methods. Calling super invokes the corresponding method in the ancestor lookup chain; its argument form determines what is forwarded. A bare super forwards the current arguments, while super() supplies none. Trace that distinction when an override decorates a result instead of replacing the entire operation.
Inheritance should preserve the contract expected by callers of the parent. A subclass that unexpectedly mutates input when its parent promises not to do so violates substitution even if its method names match. Prefer composition when one object contains or uses another rather than representing a specialized kind of it. Small cooperating objects often make state ownership and test setup clearer than a deep hierarchy built only to reuse a few lines.
class Label
def text(name); "Hi #{name}"; end
end
class Loud < Label
def text(name); super(name).upcase; end
end
puts Loud.new.text("Ada")HI ADA
The override obtains the parent’s result with the explicit argument and transforms the returned string.
Try it yourself
Explain why a Playlist should contain tracks rather than inherit from Track.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING