In object-oriented programming, inheritance allows one class to reuse the code of another class.
For instance, if you have an Animal class, a Dog class can inherit its behaviors (since a dog is a specific type of animal):
class Animal
def speak
puts "I'm an animal"
end
end
# Create Dog class that inherits from Animal
class Dog < Animal
end
Dog.new.speak
# Output: I'm an animal
This means the Dog class automatically gets the speak method from the Animal class.
Ruby Inheritance Syntax
In Ruby, inheritance is implemented using the < symbol:
class ChildClass < ParentClass
end
This tells Ruby that one class (the child) inherits from another class (the parent). For example,
class Dog < Animal
end
Here,
Dogis the child class (or subclass).Animalis the parent class (or superclass).- This means
Doginherits access to all methods of the parent class, along with the instance variables initialized by those methods.
Accessing Parent Methods and Instance Variables
Suppose the Animal class has an instance variable @name (set through the constructor) and a speak method that prints a message using that variable.
Let's see how the Dog child class can inherit this instance variable and method: