Introduction

Today, we are going to learn some interesting concepts about inheritance. You have learned this concept in other languages also. Here, you can see how it will be used and performed in the Ruby language.

Contents

Inheritance

Example

  1. Class Dog < Animal
  2. # some code
  3. End

Example

  1. Class Animal
  2. def initialize (name, color)
  3. @name = name
  4. @color = color
  5. End
  6. def speak
  7. Puts “Hi”
  8. End
  9. End
  10. Class Dog < Animal
  11. End

Example

  1. d = Dog.new (“Deva”, “Blue”)
  2. d.speak

Output

Hi

Example

  1. Class vehicle
  2. def make_sound
  3. Puts “Hi”
  4. End
  5. End
  6. Class car < vehicle
  7. End
  8. c = car.new
  9. c.make_sound

Example

  1. Class Animal
  2. def initialize (name, color)
  3. @name = name
  4. @color = color
  5. End
  6. def speak
  7. Puts “Hi”
  8. End
  9. End
  10. Class Dog < Animal
  11. End
  12. Class cat < Animal
  13. attr_accessor:age
  14. def speak
  15. Puts “Meow”
  16. End
  17. End
  18. c = cat.new (“lucy”, “white”)
  19. c.speak

Output

Meow

Example

  1. Class Animal
  2. End
  3. Class Mammal < Animal
  4. End
  5. Class Dog < Mammal
  6. End

SUPER

Example

  1. Class Animal
  2. def speak
  3. Puts “Hi”
  4. End
  5. End
  6. Class cat < Animal
  7. def speak
  8. super
  9. Puts “Meow”
  10. End
  11. End

Example

  1. c = cat.new
  2. c.speak

Output

Hi

Meow

Example

  1. Class Animal
  2. def initialize (name)
  3. @name = name
  4. End
  5. End

Example

  1. Class Cat < Animal
  2. def initialize (name, age)
  3. Super (name)
  4. @age = age
  5. End
  6. def to_s
  7. #{@name} is #{@age} years old.”
  8. End
  9. End

Example

  1. c = Cat.new (“Bob”, 3)
  2. Puts c

Output

Bob is 3 years old

Example

  1. Class A
  2. def initialize (x)
  3. Puts x/2
  4. End
  5. End
  6. Class B < A
  7. def initialize (y)
  8. Super (y +2)
  9. End
  10. End
  11. ob = B.new (6)

Output

4

CONCLUSION

I hope you understand. If you have any queryies please ask me anything. We'll see more in the future.