Thuta Learning
AdvancedProgrammingbeginner

Inheritance

Relax. We'll talk through this in plain words — no textbook voice.

Inheritance lets one class take on the behavior of another. You keep shared behavior in a parent class, and child classes can add their own extra behavior on top.

ruby
class Vehicle
  def start_engine
    puts "Engine started!"
  end
end

class Car < Vehicle
  def drive
    puts "Driving..."
  end
end

my_car = Car.new
my_car.start_engine
my_car.drive

Car < Vehicle means Car inherits from Vehicle. That's why a Car object can use start_engine.

You should see
Engine started! Driving...

Info

Use inheritance when there's an “is-a” relationship. Saying a Car is a Vehicle just feels natural.

Easy traps

  • Overusing inheritance for the sake of code reuse can make your class hierarchy messy. For small bits of shared behavior, consider a module/mixin instead.
Inheritance | Thuta Learning