How does Inheritance work in Ruby?

RubyServer Side ProgrammingProgramming

Inheritance is a key aspect of any OOP language. With the help of inheritance, we can reuse the methods that are defined on the parent class (also known as superclass) in the child class (also known as subclass).

In Ruby, single class inheritance is supported, which means that one class can inherit from the other class, but it can't inherit from two super classes. In order to achieve multiple inheritance, Ruby provides something called mixins that one can make use of.

Inheritance helps in improving the code reusability, as the developer won't have to create the same method again that has already been defined for the parent class. The developer can inherit the parent class and then call the method.

There are two important terms in inheritance and these are mentioned below −

  • Super class − A class whose characteristics are inherited by the subclass.

  • Subclass − A class that is inheriting the characteristics of the superclass.

Now that we know a little bit about the inheritance in Ruby, let's take a couple of examples to understand how it works in a better way.

Example 1

# Inheritance in Ruby

#!/usr/bin/ruby

# Super class or parent class
class TutorialsPoint

   # constructor of super class
   def initialize

      puts "Superclass"
   end

   # method of the superclass
   def super_method

      puts "Method of superclass"
   end
end

# subclass or derived class
class Learn_Ruby < TutorialsPoint

   # constructor of derived class
   def initialize

   puts "Subclass"
   end
end

# creating object of superclass
TutorialsPoint.new

# creating object of subclass
sub_obj = Learn_Ruby.new

# calling superclass method
sub_obj.super_method

Output

Superclass
Subclass
Method of superclass

Example 2

Now let's consider one more example where we will override the parent class method in the subclass with a little bit of change.

# Inheritance in Ruby

#!/usr/bin/ruby

# Super class or parent class
class TutorialsPoint

   # constructor of super class
   def initialize

      puts "Superclass"
   end

   # method of the superclass
   def super_method

      puts "superclass method"
   end
end

# subclass or derived class
class Learn_Ruby < TutorialsPoint

   # constructor of derived class
   def super_method

   puts "subclass method"
   end
end

# creating object of superclass
TutorialsPoint.new

# creating object of subclass
sub_obj = Learn_Ruby.new

# calling superclass method
sub_obj.super_method

Output

Superclass
Superclass
subclass method
raja
Updated on 25-Jan-2022 11:42:32

Advertisements