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

Inheritance

Inheritance lets a new class receive everything from an older class, like a child inheriting traits from a parent. The child then adds its own extras.

In this page:

  1. Inheritance
Syntax
ruby
class ChildClass < ParentClass
  # inherits ParentClass methods
  def new_method
    # body
  end
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using class Dog < animal in lowercase, which is a NameError.
  2. Overriding initialize in the child and forgetting to call super, so the parent's @name is never set.
  3. Expecting a class to inherit from several parents, when Ruby has single inheritance and uses modules.
🔒

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.