Inheritance

christian.dinh2481 total contributions
Published Jul 30, 2021Updated Sep 9, 2021
Contribute to Docs
In Ruby, inheritance describes the relation between classes.
Syntax
Inheritance is expressed when the <
is used to connect the parent class, Animal
, with the child class, Dog
:
class Animaldef initialize(species)@species = speciesenddef species@speciesendendclass Dog < Animaldef initialize(species, name)super(species)@name = nameendendsnoop = Dog.new("Long-Beach Labrador", "Calvin")puts snoop.species # Output: Long-Beach Labrador
The Dog
class inherits all the methods from its parent Animal
class, including .species
.
Overriding Methods
An inheriting child class can override methods defined in its parent and replace with code specific to it:
class Animaldef initialize(species)@species = speciesenddef species@speciesenddef make_sound"The animal made a sound that was hard to tell."endendclass Dog < Animaldef initialize(species, name)super(species)@name = nameenddef name@nameenddef make_sound"Bark!"endendsnoop = Dog.new("Long-Beach Labrador", "Calvin")puts snoop.make_sound # Output: Bark!
The .make_sound
method from Animal
was overridden in Dog
with a return string specific to that class.
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- BrandonDusch580 total contributions
- christian.dinh
- Anonymous contributor
- BrandonDusch
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.