Ruby - Class Inheritance

Introduction

Because of inheritance classes lower down in hierarchy get the features of those higher up.

At the same time it can add specific features of their own.

Ruby doesn't support multiple inheritance.

Demo

class ParentClass 
  def method1 #  w w  w.  j  a  v  a 2  s. c  o m
    puts "Hello from method1 in the parent class" 
  end 

  def method2 
    puts "Hello from method2 in the parent class" 
  end 
end 

class ChildClass < ParentClass 
  def method2 
    puts "Hello from method2 in the child class" 
  end 
end 

my_object = ChildClass.new 
my_object.method1 
my_object.method2

Result

First you create the ParentClass with two methods, method1 and method2.

Then you create ChildClass and make it inherit from ParentClass using the ChildClass < ParentClass notation.

Last, you create an object instance of ChildClass and call its method1 and method2 methods.

Related Topics