Inheritance in Ruby: Exploring Attributes and Methods
Introduction
Welcome back! In this part of our Ruby Class Basics Review, we’ll dive into inheritance, a core concept in Ruby’s object-oriented programming (OOP). Inheritance enables code-sharing between classes, making our code more efficient and easier to read.
This lesson covers how inheritance works in Ruby, including attribute and method inheritance, along with the super keyword to access superclass functionality. Ready to dive in? Let’s get started!
Defining Inheritance
Inheritance in Ruby allows us to create a subclass that inherits attributes and methods from a superclass. This approach is especially useful when multiple classes share common features or behaviors.
Let’s explore with a superclass named Vehicle and a subclass named Car:
In this example, Car inherits properties from Vehicle. Ruby supports several types of inheritance, but here we’re focusing on single inheritance, where a subclass has a single superclass.
Attribute Inheritance with attr_reader
With attribute inheritance, a subclass can inherit instance variables from its superclass.
The Musician class inherits the @name attribute from Artist, while also introducing its own attribute, @instrument. Getters can be conveniently defined using attr_reader to access instance variables of each class.
Method Inheritance
