← Back to Ruby Course | Chapter 9: OOP | Lesson 5 of 7

Inheritance

In this page:

  1. Inheritance

Inheritance

A class inherits from another with class Dog < Animal, gaining all of the parent's public and protected methods. This models an "is-a" relationship, like a Dog being a kind of Animal. Ruby only supports single inheritance for classes -- a class can have just one direct superclass, though modules (covered later) offer another way to share behavior.

Note: Ruby supports single inheritance only for classes -- use modules (Mixins) to share behavior across unrelated class hierarchies.

Example: Inheritance

markup
class Animal
  def initialize(name)
    @name = name
  end

  def eat
    puts "#{@name} is eating"
  end
end

class Dog < Animal
  def bark
    puts "#{@name} says Woof!"
  end
end

rex = Dog.new("Rex")
rex.eat
rex.bark
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.