Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Classes and Modules

Inheritance and Abstract Classes

Learn Crystal inheritance with the < operator, super, method overriding, abstract classes and methods, protected and private visibility, virtual types and polymorphism with Ruby stand-ins.

Inheritance lets one class build on another. The subclass gets all the methods of its parent and may add or replace some. Combined with polymorphism, where code works with the parent type but each object runs its own version of a method, inheritance is a core tool for modelling families of related things. This lesson shows the syntax, super, abstract classes and how Crystal's type system treats a parent type.

Crystal listings are read-only here. The Ruby stand-ins run the same designs; Ruby has no abstract keyword, so the stand-in simulates it.

Subclassing

Use < to inherit:

CRYSTAL
class Animal
  def initialize(@name : String)
  end

  def speak : String
    "..."
  end

  def intro : String
    "#{@name} says #{speak}"
  end
end

class Dog < Animal
  def speak : String
    "Woof"
  end
end

class Cat < Animal
  def speak : String
    "Meow"
  end
end

puts Dog.new("Rex").intro     # Rex says Woof
puts Cat.new("Tom").intro     # Tom says Meow

Dog and Cat inherit initialize and intro from Animal. They override speak. Note that intro is written once and calls speak; which version runs depends on the real class of the object. That is polymorphism.

A class can have only one parent (single inheritance). Everything ultimately descends from Object; classes with no < inherit directly from it.

super

super calls the parent's version of the current method. Inside initialize it runs the parent's constructor:

CRYSTAL
class Puppy < Dog
  def initialize(name : String, @age_months : Int32)
    super(name)                 # sets @name in Animal
  end

  def speak : String
    super + "!"                 # "Woof" + "!"
  end
end

puts Puppy.new("Bit", 3).intro  # Bit says Woof!

A bare super with no parentheses passes along the same arguments the current method received. super() passes none.

Ruby Stand-in: inheritance and super in Ruby

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.

Abstract classes and methods

Sometimes a parent should not be created directly and should force children to provide a method. Mark them abstract:

CRYSTAL
abstract class Shape
  abstract def area : Float64

  def describe : String
    "#{self.class.name} with area #{area.round(2)}"
  end
end

class Circle < Shape
  def initialize(@radius : Float64)
  end

  def area : Float64
    Math::PI * @radius ** 2
  end
end

class Rect < Shape
  def initialize(@w : Float64, @h : Float64)
  end

  def area : Float64
    @w * @h
  end
end

puts Circle.new(1.0).describe    # Circle with area 3.14
puts Rect.new(2.0, 3.0).describe # Rect with area 6.0

Shape.new is a compile error, because the class is abstract. A subclass that forgets to implement area also fails to compile, before the program runs. In Ruby the same mistake shows up only when somebody calls the missing method.

The Ruby stand-in below simulates the "must implement" rule with NotImplementedError, to show the idea in a language that cannot check it ahead of time:

Ruby Stand-in: simulating abstract methods in Ruby

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.

Visibility and inheritance

  • public methods are callable from anywhere.
  • protected methods are callable on other instances of the same class or subclasses, from within the class.
  • private methods can be called only without a receiver (helper, not obj.helper), but are still inherited and callable from subclass methods.
CRYSTAL
class Account
  def initialize(@balance : Int32)
  end

  def richer_than?(other : Account) : Bool
    balance > other.balance
  end

  protected def balance
    @balance
  end
end

a = Account.new(100)
b = Account.new(50)
puts a.richer_than?(b)    # true
# a.balance                # compile error: protected method

Virtual types

When you declare a variable or parameter as Animal, it can hold a Dog, a Cat or any other subclass. The compiler treats this as a virtual type Animal+, "Animal or any of its subclasses". Calls on it are dispatched at run time to the right class, like a vtable in C++, and the compiler checks that every possible subclass has the called method.

CRYSTAL
pets = [Dog.new("Rex"), Cat.new("Tom")] of Animal
pets.each { |pet| puts pet.intro }

of Animal tells the compiler the array's element type is Animal, not a union of Dog | Cat. Both work, but the explicit of Animal is what you want when more subclasses may appear later.

Checking and converting classes

CRYSTAL
rex = Dog.new("Rex")
puts rex.is_a?(Animal)       # true
puts rex.is_a?(Cat)          # false
puts rex.class               # Dog
puts rex.class.superclass    # Animal

Use is_a? and case/when to branch on a subclass, but treat repeated type checks as a smell: it usually means the behaviour belongs in a method overridden by each class.

Composition over inheritance

Inheritance models "is a" (a Dog is an Animal). When you only want to reuse behaviour, prefer composition (an object has a helper) or modules (see modules and mixins). Deep inheritance trees are hard to change: a tweak in a base class affects every descendant. A good rule is to keep hierarchies shallow, and to make parents abstract when they exist only to define a contract.

finalize... and previous_def

Two small, advanced tools you may meet: previous_def calls the previous definition of the same method when you reopen a class and redefine it, and super always goes upwards in the hierarchy. You can reopen any class, even a standard-library one, to add methods; do this carefully and in one clearly named file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you declare that Dog inherits from Animal?

    Crystal uses the less-than sign, like Ruby.
  2. 2. What happens if a concrete subclass forgets to implement an abstract method?

    The compiler checks abstract methods, so the program does not build.
  3. 3. What does a bare super (no parentheses) do inside a method?

    super without parentheses forwards the current arguments; super() sends none.
  4. 4. What does [Dog.new("a"), Cat.new("b")] of Animal achieve?

    It sets the array type to Array(Animal) instead of inferring a union of the two classes.

Summary

  • class Child < Parent inherits methods and instance variables; override methods and call the parent's with super.
  • Polymorphism: code written for the parent runs each object's own version of a method.
  • abstract class and abstract def force subclasses to provide behaviour, and the compiler enforces it.
  • private and protected control access; a parent type is a virtual type that stands for all its subclasses.
  • Prefer shallow hierarchies, composition and modules over deep inheritance.

Next: Structs and Value Types