Ruby - Inheritance Example

1. Introduction

Inheritance is a fundamental concept in object-oriented programming that allows for code reuse and the creation of hierarchical relationships between classes. In Ruby, inheritance allows a class (subclass) to inherit features and behavior from another class (superclass). This post will guide you through the concept of inheritance in Ruby, demonstrating how to use it efficiently.

Definition

In inheritance in Ruby, a class (often referred to as the subclass or derived class) can inherit attributes and methods from another class (known as the superclass or base class). This allows the subclass to reuse the code of the superclass and extend or override specific functionalities. In Ruby, inheritance is indicated by the < symbol followed by the superclass name.

2. Program Steps

1. Define a superclass with attributes and methods.

2. Create a subclass using the < symbol followed by the superclass's name.

3. In the subclass, you can override or add new methods.

4. Instantiate objects of the subclass and use both inherited and new methods.

3. Code Program

# Define the superclass
class Animal
  def speak
    "I am an animal!"
  end
end
# Define a subclass that inherits from Animal
class Dog < Animal
  # Override the speak method
  def speak
    "Woof!"
  end
end
# Define another subclass that inherits from Animal
class Cat < Animal
  # Add a new method specific to Cat
  def purr
    "Purr..."
  end
end
# Create an instance of the Dog class
dog = Dog.new
puts dog.speak
# Create an instance of the Cat class
cat = Cat.new
puts cat.speak
puts cat.purr

Output:

Woof!
I am an animal!
Purr...

Explanation:

1. We start by defining a superclass named Animal with a speak method.

2. Next, we define a subclass named Dog that inherits from the Animal class. Inside the Dog class, we override the speak method to return "Woof!" instead.

3. We then define another subclass called Cat that also inherits from Animal. In addition to the inherited speak method, the Cat class has a new method named purr.

4. We instantiate an object of the Dog class and call its speak method, which displays "Woof!".

5. Similarly, we instantiate an object of the Cat class. Calling the speak method on this object uses the method from the superclass (Animal), resulting in "I am an animal!". Additionally, we can call the purr method specific to the Cat class, which displays "Purr...".

Through inheritance, classes can reuse code from other classes and also introduce unique behaviors, promoting a hierarchical and organized code structure.


Comments