Inheriting what's shared: inheritance
With objects you built 'one thing' (lesson 12). But make a dog, a cat, a bird as objects, and name, age, eating keep repeating the same. Gathering the shared parts in one place and letting each inherit them is inheritance.
The parts that keep repeating
A dog, a cat, a bird can all be objects.
But put the three side by side,
and name, age, eating go into all three the same.
That's writing the same thing three times.
The more kinds you add, the bigger this overlap grows.
Look at dog, cat, bird. The repeating tags glow together.
The overlap is plain to see.
If you rewrite the same thing in every object,
fixing one means fixing them all by hand.
So where should we gather this common part?
Gather the common part upward
Pull the repeating name, age, eating
up into one place above.
There you put a parent called 'Animal'.
Now the common part lives in Animal alone.
Dog, cat, bird become its children below.
Tap to gather the common parts up. One 'Animal' parent appears.
With the common part gathered in one spot,
the children got much lighter.
But now the children have no name, age, eating?
They didn't lose it; they receive it from the parent.
Inherit the parent's stuff as-is
A child automatically has all the parent has.
The dog inherits Animal's name, age, eating
without writing them again.
So the dog is already a full animal.
It received them; it didn't copy them out.
Pick a child. The parent's tags come down and fill it in.
Dog, cat, and bird
all inherited the same from the parent Animal.
But if they're only identical, they aren't kinds.
Dogs bark, birds fly. How do we add that?
Add your own on top of what you got
Keep the inherited common part as-is,
and lay your own on top of it.
The dog adds 'bark', the bird adds 'fly'.
Same parent, but different additions,
so dog and bird become different kinds.
Add the child's own tag. It differs in color from the inherited ones.
Now the dog is 'Animal's common part + bark'.
The received and the added became one.
Common in the parent, differences in the child.
Thanks to this, one big payoff follows.
Fix once, and all change together
Here's the real power of inheritance.
Add 'sleep' to the parent 'Animal' once,
and dog, cat, and bird can all suddenly sleep.
Every child changes together, untouched one by one.
Duplication vanishes, so mistakes shrink with it.
From values we built 'things' with objects,
and with inheritance we tidied those things together.
Now we hold a fairly large program.
But a program is bound to go wrong somewhere.
Next, we'll learn to find and fix what went wrong.