Classes
Ruby Inheritance
Class Inheritance
Ruby inheritance uses < for single inheritance.
Introduction to Ruby Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit features from another class. In Ruby, inheritance is implemented using the <
symbol, which signifies that a class is inheriting from a superclass. This concept of inheritance is often used to reuse code and establish a hierarchical relationship between classes.
Defining a Superclass and Subclass
To illustrate how inheritance works in Ruby, let's define a superclass named Animal
and a subclass named Dog
. The subclass will inherit the attributes and methods of the superclass.
Adding Methods to the Subclass
While the Dog
class inherits the speak
method from Animal
, it can also have its own methods. Let's add a method called bark
to the Dog
class.
Overriding Methods in the Subclass
Inheritance allows subclasses to override methods of the superclass. This is useful when the subclass needs to alter or extend the behavior of the inherited methods. Let's override the speak
method in the Dog
class.
Conclusion
Ruby inheritance is a powerful feature that enables code reuse and a clear class hierarchy. By using the <
symbol, you can easily define subclasses that inherit from superclasses, override methods, and extend functionality. Understanding inheritance is crucial for writing efficient and organized Ruby code.
Classes
- Classes
- Inheritance
- Modules as Mixins
- Structs
- Enums
- Instance Variables
- Previous
- Classes
- Next
- Modules as Mixins