Classes and inheritance
A class is a template for objects that share the same shape and behavior.
constructor(...) runs once when you create an instance with new - it's
where you set the instance's own properties with this.property = value.
Methods defined in the class body are shared by every instance instead of
copied onto each one.
class Dog extends Animal builds a subclass: Dog gets every method Animal
has for free, and only needs to define what's different. Overriding a method -
writing a same-named method in the subclass - replaces the parent's version for
instances of the subclass, without touching how Animal itself behaves.
Your task: write class Animal with a constructor that stores name, and
a method speak() returning "<name> makes a sound". Then write class Dog,
extending Animal, that overrides speak() to return "<name> barks"
instead.
You'll practice:
Writing a constructor and a method on a class
Extending a class and overriding one of its methods
Show a hint
Show solution
Related reading: What OOP Actually Is →
Previous Next