A class can have an inheritance relation with a super class. The sub class inherits all the attributes and methods from the super class.

If an object is created using a sub class, it has the methods and attributes of both the sub class and the super class. You can have multiple sub classes that inherit from the same super class.

Download Free Ruby Ebook

Inheritance in ruby

Inheritance example

The ruby program below creates an object with the defined sub class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/ruby

class Bird
def quack
puts "Quack"
end
end


class Parrot < Bird
def talk
puts "I like ruby"
end
end

obj = Parrot.new()
obj.talk()
obj.quack()

The above program defines a super class: Bird. Then a sub class is defined (parrot). The sub class inherits all attributes and methods from the super class.

Finally we create an object. The object has both the methods and attributes of the super class and the sub class.

Exercises

  1. Can a class inherit from 2 super classes?
  2. Can super classes inherit from other super classes?
  3. Add another class that inherits from the super class bird.