class Child < Parent
The symbol every Rails core course used, unexplained
class Article < ApplicationRecord
end
This line has appeared since the first Rails core course. The Ruby classes & initialize course explained class, initialize and attr_accessor. That covers every part of this line except one character: <. The symbol means inheritance: Article inherits from ApplicationRecord. This course explains what that gets you.
A second BankAccount, built from the first
class BankAccount
def initialize(starting_balance)
@balance = starting_balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
return "insufficient funds" if amount > @balance
@balance -= amount
end
def balance
@balance
end
end
class SavingsAccount < BankAccount
end
savings = SavingsAccount.new(100)
savings.deposit(50)
savings.balance
# => 150
The body of SavingsAccount is empty. It defines no deposit, no withdraw and no balance, yet savings.deposit(50) and savings.balance both work. class SavingsAccount < BankAccount makes every method BankAccount defines available on SavingsAccount too, without copying a line.
SavingsAccount is a BankAccount
savings.is_a?(BankAccount)
# => true
savings.class
# => SavingsAccount
savings.class is still SavingsAccount, its own class, and is_a?(BankAccount) is also true. Inheritance doesn't rename SavingsAccount. It makes it a kind of BankAccount, so anywhere code expects a BankAccount, a SavingsAccount fits.
Why not copy the methods
Writing deposit, withdraw and balance a second time inside SavingsAccount would also work. Then BankAccount needs a fix or a new method, and every copy has to be updated by hand. With class SavingsAccount < BankAccount there is one definition, every subclass reuses it, and no copy can drift out of sync.
What this course covers
- class Child < Parent: inheriting a parent's methods (this lesson)
- Overriding a Parent Method: replacing inherited behavior on purpose
- Calling super: reusing a parent method's logic instead of throwing it away
- The Ancestors Chain:
.ancestors, the lookup path Ruby follows - ApplicationRecord Is Inheritance Too: connecting this to
Article - Choosing Inheritance Wisely: when
<fits, and when it doesn't - Putting It Together: a small hierarchy combining everything, pointing at modules next
The course ends at Article's chain: Article inherits from ApplicationRecord, which inherits from ActiveRecord::Base. Lesson 4 checks that chain on this app's Catalog::Course.
Keep going with lesson 2
Overriding a parent method
OverdraftAccount redefines withdraw, and Ruby runs the child's version first while other inherited methods stay unchanged.
A free account also gives you the quizzes, your progress and notes, and the discussion.