English

Inheritance

Choosing a superclass

If you write another class name after the class name, the class inherits from that class. You can use the superclass's instance variables and methods as they are.

Emojicode
🐇 🐾 🍇
  🖍🆕 name 🔡
  🆕 🍼 name 🔡 🍇🍉

  ❗️ 🗣 🍇
    😀 🔤🧲name🧲 made a sound🔤❗️
  🍉

  ❗️ 🚶 🍇
    😀 🔤🧲name🧲 walked🔤❗️
  🍉
🍉

🐇 🐕 🐾 🍇
  ✒️ ❗️ 🗣 🍇
    😀 🔤🧲name🧲: Woof!🔤❗️
  🍉
🍉

🏁 🍇
  🆕🐕 🔤Rex🔤❗️ ➡️ rex
  🗣 rex❗️
  🚶 rex❗️
🍉
Output
Rex: Woof!
Rex walked

🐇 🐕 🐾 means “🐕, which inherits from 🐾.” 🐕 has no 🆕 of its own, so the superclass's 🆕 is used as is.

Overriding (✒️)

When you redefine a superclass method in a subclass, put ✒️ in front of it. If you forget it, you get a compile error, so you can never override a method by accident.

Example of a compile error
🐇 🐾 🍇
  🆕 🍇🍉
  ❗️ 🗣 🍇
    😀 🔤…🔤❗️
  🍉
🍉

🐇 🐕 🐾 🍇
  ❗️ 🗣 🍇
    😀 🔤Woof🔤❗️
  🍉
🍉

🏁 🍇
  🗣 🆕🐕❗️❗️
🍉

Calling the superclass's method (⤴️)

To call the superclass's method from inside an overriding method, use ⤴️.

Emojicode
🐇 🐾 🍇
  🆕 🍇🍉
  ❗️ 🗣 🍇
    😀 🔤(animal sound)🔤❗️
  🍉
🍉

🐇 🐕 🐾 🍇
  ✒️ ❗️ 🗣 🍇
    ⤴️🗣❗️
    😀 🔤Woof!🔤❗️
  🍉
🍉

🏁 🍇
  🗣 🆕🐕❗️❗️
🍉
Output
(animal sound)
Woof!

When you write an initializer in a subclass, call the superclass's initializer inside it with ⤴️🆕 …❗️.

Emojicode
🐇 🐾 🍇
  🖍🆕 name 🔡
  🆕 🍼 name 🔡 🍇🍉
  ❗️ 🏷 ➡️ 🔡 🍇
    ↩️ name
  🍉
🍉

🐇 🐈 🐾 🍇
  🖍🆕 lives 🔢
  🆕 name 🔡 🍇
    9 ➡️ 🖍lives
    ⤴️🆕 name❗️
  🍉
  ❗️ 📋 🍇
    😀 🔤🧲🏷👇❗️🧲 has 🧲🔡 lives❗️🧲 lives🔤❗️
  🍉
🍉

🏁 🍇
  📋 🆕🐈 🔤Tama🔤❗️❗️
🍉
Output
Tama has 9 lives

Store values in the subclass's instance variables first, and then call the superclass's initializer.

Treating instances as the superclass type

You can put instances of a subclass into variables or lists of the superclass type. When you call a method, each subclass's own method runs.

Emojicode
🐇 🐾 🍇
  🆕 🍇🍉
  ❗️ 🗣 ➡️ 🔡 🍇
    ↩️ 🔤…🔤
  🍉
🍉

🐇 🐕 🐾 🍇
  ✒️ ❗️ 🗣 ➡️ 🔡 🍇
    ↩️ 🔤Woof🔤
  🍉
🍉

🐇 🐈 🐾 🍇
  ✒️ ❗️ 🗣 ➡️ 🔡 🍇
    ↩️ 🔤Meow🔤
  🍉
🍉

🏁 🍇
  🆕🍨🐚🐾🍆❗️ ➡️ 🖍🆕 animals
  🐻 animals 🆕🐕❗️❗️
  🐻 animals 🆕🐈❗️❗️
  🔂 a animals 🍇
    😀 🗣 a❗️❗️
  🍉
🍉
Output
Woof
Meow