In today's blog post we will be diving into class inheritance from a Ruby perspective.
If you need a refresher about classes, you can read my previous blog post here.
Classes are blueprints for creating objects. So if you wanted to create a new object that needed a new blueprint you would create a new class.
However, this can create repetition. Let's look at an example of this.
class Cat def endothermic true end def live_birth true end end
class Dog def endothermic true end def live_birth true end end
We can improve the cat and dog class by using inheritance. If we create a superclass that contains the methods that are common to both the cat and dog class, then we can have the classes inherit from the superclass.
class Mammal def endothermic true end def live_birth true end end
Now that we have a Mammal class, we can now use inheritance to DRY up our code. The "<" indicates that this is an inheritance.
class Cat < Mammal end class Dog < Mammal end annabelle = Dog.new stella = Cat.new puts stella.endothermic # output true puts annabelle.endothermic # output true
In Ruby, a class can only have one parent that they inherit from. However, modules can be a way around this constraint.
The next blog post will cover super and modules.