ruby · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
builds a new class on top of an old one.
Dogs and cats are both pets, so why write everything twice? class Dog < Pet makes Dog a of Pet. Through inheritance, a Dog gets every method Pet has, and you add only what is special about dogs.
To a method, write one with the same name in the subclass, and Ruby uses that version instead. Inside it, runs the inherited version, so you can add to it instead of starting again.
class Pet
def describe
"a friendly pet"
end
end
class Dog < Pet
def describe = "#{super} who loves walks"
end
puts Dog.new.describe
p Dog.superclass A one-line method can skip its end: write def describe = and then the answer.
guess first
Penguins are birds too. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Bird
def move = "flaps its wings"
def eat = "pecks at seeds"
end
class Penguin < Bird
def move = "waddles"
end
pingu = Penguin.new
puts pingu.move
puts pingu.eat
your turn
Your turn. Make a friendlier robot.
Finish the friendly robot's greeting with a sentence of your own. super drops in the plain robot's greeting first.
fix it
The dog cannot even hold its own name. Fix it!
- Read the error. Dog has no method called
name=. Where was that method meant to come from? attr_accessorlives in Pet, but Dog is not built on Pet, so it inherits nothing.- Change line 5 to class Dog < Pet, then press run.
nailed it
your classes have a family tree now. :D
class Dog < Petinherits every method from Pet.- Write a method with the same name to override it.
superruns the inherited version from inside.
new words in your collection
- inheritance
- subclass
- override
- super
This lesson isn’t saved. A free account remembers every lesson you finish.