Challenge - Class hierarchy
Build an employee-manager hierarchy with classes, extends, super and static.
Class hierarchy
In this challenge you will build an employee-manager hierarchy. First you define an Employee class with class; its constructor takes name and assigns it to this.name.
Then you derive a Manager class with extends Employee. In the derived constructor the super(name) call runs the parent constructor; you must do this before using this.
Finally you add a class-level method with the static keyword — it lives on the class itself, not on instances.
Exercise Write the Employee and Manager classes
Write an Employee class whose constructor takes name and assigns it to this.name. Then derive a Manager class with extends Employee; its constructor takes name and dept, calls super(name) and assigns this.dept. Finally add a static method to Manager.
Show example solution
Start with class Employee { constructor(name) { this.name = name; } }. Then write class Manager extends Employee { constructor(name, dept) { super(name); this.dept = dept; } static create(name) { return new Manager(name, 'General'); } }.
Example solution:
class Employee {
constructor(name) {
this.name = name;
}
}
class Manager extends Employee {
constructor(name, dept) {
super(name);
this.dept = dept;
}
static create(name) {
return new Manager(name, 'General');
}
}
Test yourself
-
What does the super(name) call do?
class Manager extends Employee { constructor(name, dept) { super(name); this.dept = dept; } }- Calls the subclass constructor
- Calls the parent class constructor
- Defines a static method
- Creates a new instance
Show answer
Calls the parent class constructor — Correct! super(name) runs the parent constructor and prepares this.
-
Derive the Manager class
class Manager ____ { constructor(name, dept) { super(name); this.dept = dept; } }Show answer
class Manager extends Employee { constructor(name, dept) { super(name); this.dept = dept; } } -
Match the class concepts
- extends
- Subclass declaration
- super(...)
- Parent constructor
- static
- Class-level method
- class
- Class declaration