Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 134 ยท Object-Oriented Ruby

Inheritance

Learn Ruby inheritance - subclasses with <, overriding methods, super with and without arguments, the ancestors chain, Object and BasicObject, abstract methods, and when to prefer composition.

Suppose you are writing software for a zoo. Dogs and cats both have a name, both eat, both make a sound. If you wrote two separate classes you would copy the name handling twice, and every future fix would have to be made twice. Inheritance solves this: you write the shared behaviour once in a superclass (also called parent or base class), and each subclass (child) automatically gets all of it, then adds or changes what makes it special.

Inheritance models an is-a relationship: a Dog is an Animal. Ruby supports single inheritance, which means a class has exactly one direct parent. (Sharing behaviour across unrelated classes is the job of modules, covered in Modules and Mixins.) This lesson shows how to declare subclasses, override methods, call the parent with super, follow the lookup chain with ancestors, write "abstract" methods, and decide when inheritance is the wrong tool. You should know Classes and Objects and Instance and Class Methods.

Subclasses with <

You declare a parent with < after the class name. The subclass inherits every public and protected method of the parent, and the parent's initializer too, unless it defines its own.

Ruby A subclass inherits behaviour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Dog has no body at all, yet it can be created with a name and can eat, because everything came from Animal. Cat overrides speak: its own version is found first and wins. Dog keeps the parent's version, which just returns "...".

Notice the questions at the end. is_a? is true for the class and all its ancestors, while instance_of? is true only for the exact class. And Dog < Animal asks "is Dog a descendant of Animal?" (true), while Animal < Dog answers false. The comparison returns nil when two classes are unrelated.

Overriding and super

Overriding replaces the parent's method completely. Often you want to extend it: do the parent's work, then add your own. The keyword super calls the same-named method in the parent class.

Ruby Extending a parent method with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Car#initialize takes only a name and passes the extra information up with super(name, 4). If you forget to call super in initialize, the parent's setup never runs and its instance variables stay nil, a common source of mysterious bugs.

The three forms of super

super behaves differently depending on how you write it:

Form What is passed to the parent
super (bare, no parentheses) the same arguments the current method received (including keywords and the block)
super() no arguments
super(a, b) exactly those arguments

The bare form is convenient and also a classic trap, as this example shows.

Ruby Bare super passes the arguments through (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Square#initialize received one argument, and bare super forwarded it to Shape#initialize, which takes none. Ruby stops with main.rb:2:in 'Shape#initialize': wrong number of arguments (given 1, expected 0) (ArgumentError). The fix is super() with explicit empty parentheses, which means "call the parent with nothing".

Method lookup and ancestors

When you call object.method_name, Ruby searches for the method in a fixed order: first the object's class, then its parent, then the grandparent, all the way up. The first match wins. You can see this order with ancestors.

Ruby The lookup chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The chain for Dog is [Dog, Mammal, Animal, Object, Kernel, BasicObject]. Dog finds who in Mammal first. kind lives in Animal, but when it calls who, Ruby starts the search again from the object's class (Dog), so it finds Mammal#who. This is polymorphism at work: the parent's code adapts to whichever subclass it runs in. Dog.instance_methods(false) lists only methods defined in Dog itself.

At the top of every chain sit two special classes. Object is the default parent of any class that does not name one, and it brings Kernel (with puts, p, raise, ...). BasicObject is the bare root, with almost no methods; BasicObject.superclass is nil. You rarely inherit from it directly, except for special "blank slate" proxies.

Abstract methods

Many designs have a parent that defines the shape of an algorithm and leaves a gap for children to fill. Ruby has no abstract keyword. The convention is to raise NotImplementedError in the parent.

Ruby A template method with an abstract step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

render is the template method: it fixes the order (header, body, footer) and the subclasses supply the details. A missing piece fails with a message naming the class that forgot it. One surprise: NotImplementedError is not a StandardError, as the last line shows (it descends from ScriptError), so a plain rescue => e does not catch it. Rescue it by name, as above.

Reopening vs. subclassing, and the superclass mismatch

If you write class Dog < Animal twice, the second is a reopening of the same class and must name the same parent. Naming a different parent is an error:

Ruby Superclass mismatch (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby reports main.rb:7:in '<main>': superclass mismatch for class Dog (TypeError). You can also write class Dog without a parent to reopen the existing class and add methods. Be careful with that when two files accidentally use the same class name.

Inheritance or composition?

Inheritance is powerful, but it couples a child tightly to its parent. Every change to the parent can break children, and a deep tree is hard to follow. A useful test: is it truly an is-a relationship that will stay true? A Dog is an Animal, yes. But is a Stack a kind of Array? Inheriting from Array would expose shift, insert and sort! on your stack, breaking its promise. A better design has an array inside and exposes only push, pop and peek: this is composition.

Ruby Composition instead of inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Rules of thumb that experienced Rubyists follow:

  • Prefer composition when you only want to reuse code, and inheritance when you want to substitute one type for another.
  • Keep hierarchies shallow, two or three levels at most.
  • Do not inherit from core classes like Array, Hash or String unless you have a strong reason; their methods often return the base class, not your subclass.
  • Share behaviour across unrelated classes with modules, not inheritance (see Modules and Mixins and Duck Typing and Polymorphism).
  • Call super in initialize unless you deliberately replace the parent's setup.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class Dog < Animal; end, which expression is true for d = Dog.new("Rex")?

    is_a? is true for the class and its ancestors. instance_of? requires the exact class, and Dog's superclass is Animal.
  2. 2. What does a bare super (no parentheses) inside a method do?

    Bare super forwards the current arguments. Use super() to pass none, which avoids ArgumentError when the signatures differ.
  3. 3. How does Ruby find a method called on an object?

    The ancestors list is the search order, starting with the receiver's class.
  4. 4. Why does rescue => e not catch a NotImplementedError?

    A bare rescue catches StandardError and its subclasses. Rescue NotImplementedError by name.
  5. 5. Which is the best reason to choose composition over inheritance?

    When the relationship is not truly is-a, holding the object inside and exposing a small interface keeps the contract tight.

Summary

  • class Child < Parent makes Child inherit the parent's methods; Ruby allows exactly one direct superclass.
  • An overriding method replaces the parent's; super calls the parent's version.
  • Bare super forwards the current arguments, super() passes none, super(a, b) passes exactly those; forgetting to call super in initialize skips the parent's setup.
  • ancestors shows the lookup order; every chain ends in Object, Kernel and BasicObject.
  • is_a? includes ancestors, instance_of? is exact; Dog < Animal compares classes.
  • Mark abstract methods by raising NotImplementedError (rescue it by name).
  • Prefer composition when the relationship is not truly is-a, and keep hierarchies shallow.

Next: Modules and Mixins