OOP: Inheritance & Super
Inheritance derived child subclasses from parent base classes. Ruby supports single inheritance and provides the super keyword to invoke parent methods.
1 Overrides & Constructor Chaining using super
In Ruby, subclasses inherit from parent classes using the **`<`** symbol: `class Sub < Parent`. When overriding a parent method, you can invoke the parent class's original implementation by calling **`super`**.
2 Inheritance Code
Let's run a program demonstrating class inheritance, overrides, and invoking parent methods with super:
Ruby — Inheritance
▶ Run Code
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
"Generic animal sound"
end
end
# Dog inherits from Animal
class Dog < Animal
def speak
# Call parent method, append child implementation details
super + " - Woof! Woof!"
end
end
dog = Dog.new("Buddy")
puts dog.speak
3 Code Challenge
Challenge: Write a parent class called `Vehicle` and a child subclass called `Truck`. Override a method `drive` in `Truck` that invokes `super` to print the parent message first, followed by a custom truck message.