Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 16 / 68

Inheritance (Extending a Class)

In this lesson you will learn class inheritance in Ruby so you can design classes that share functionality efficiently. This is for anyone searching for "Ruby inheritance how to use".

Writing class Child < Parent creates a new class that carries over the parent's functionality. This is called inheritance. It is the classic object-oriented technique of taking a shared "animal" blueprint and adding each animal's own way of making a sound.

The sample code makes Dog inherit from the parent Animal and redefines the speak method for itself (overriding). The instance created with Dog.new("Rex") has both the @name inherited from Animal and Dog's own speak.

A common stumbling block for beginners is initialising the parent when the child defines its own initialize. If the child does not define one, the parent's is used automatically; if it does, you have to call the parent's initialisation with super.

Gathering the shared parts into a parent class saves you writing the same code repeatedly. It is an important idea in large application design too.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)