What is inheritance in Ruby?

Ruby is an object-oriented language that supports inheritance. It supports single class inheritance, but multiple class inheritance is not supported.

Inheritance

Inheritance offers reusability. This means that the functions and variables already declared in one class can be reused in another class by making it a child of that class. This prevents the need for extra, redundant code in the new class that is being declared.

Every class in Ruby has a parent class by default. Since Ruby 1.9 version, BasicObject class is the parent class of all other classes in Ruby.

Keywords

Inheritance involves the use of super and sub-classes.

  • super class: This is the class from which the functions and variables are inherited. This is the parent class, also known as the base class.
  • sub class: This is the class that inherits functions and variables from the super class. This is the child class, also known as the derived class.

Overriding inherited class

In the case that both the super class and the sub class have a function of the same name, the method associated with the sub class will be executed, i.e. the inherited function will be over-ridden.

This is a special feature of inheritance in Ruby.

Code

The following code shows how a subclass object can access a super class function:

# Inheritance in Ruby
# this is the super class
class Educative
# constructor of super class
def initialize
puts "Super class constructor"
end
# method of the superclass
def super_adder(x, y)
puts "Using method of superclass:"
return x+y
end
end
# subclass or sub class
class Edpresso < Educative
# constructor of sub class
def initialize
puts "Sub class constructor"
end
end
# creating object of superclass
Educative.new
# creating object of subclass
sub_obj = Edpresso.new
# calling the method of super class using sub class object
added = sub_obj.super_adder(2,3)
print "sum = ", added

In the above code, the class Edpresso inherits the base class Educative using the < symbol.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved