A subclass that overrides and extends
name is set by Animal, then the Dog field tricks, then breed. Dog.create is inherited from Animal, and new this builds a Dog because it was called as Dog.create.
class Child extends Parent makes a class that starts with everything Parent has and adds or changes parts; super(...) runs the parent's constructor, super.method() calls the parent's version of a method you override, and instanceof checks the whole family line.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write class Vehicle with constructor(wheels) and describe() returning "A vehicle with N wheels", and class Bike extends Vehicle that passes 2 to super and overrides describe() to add " and a bell" using super.describe().
Write class NotFoundError extends Error that takes a resource name, sets the message to "<resource> not found", sets name, and stores status = 404. Throw and catch it, and log the error and its status.
Write class SortedList extends Array with an add(value) method that inserts the value and keeps the array sorted ascending (numbers). Add 5, 1, 3 and log the array with Array.from.
Explain it without notes
What does class B extends A set up, in terms of prototypes?
Why must a subclass constructor call super() before using this?
How do you override a method but still use the parent's behaviour?
What is the construction order of a subclass instance, and what bug can it cause?
Preview
Console
Nothing logged yet.Expected console output
Dog { name: 'Rex', tricks: [ 'sit' ], breed: 'Labrador' }
Rex makes a sound, then barks
Milo makes a sound
true true false
Dog { name: 'Bolt', tricks: [], breed: undefined }