Summary - Classes
- JavaScript course
- Advanced
- Lesson 12/100
- 5 min
Build a geometric shape class hierarchy with extends, super and static.
Summary - Classes
In this group you learned the basics of classes:
- You define a template with
class. - A
constructorinitializes a new instance; you create one withnew. - Methods reach the instance through
this. extendscreates a subclass;super()calls the parent constructor.staticmembers belong to the class.
Now let us build a hierarchy that brings these together.
Practice Shape hierarchy
Declare a base Shape class whose area() method returns 0. Then declare a Circle subclass with extends: its constructor takes radius, calls super(), and assigns this.radius; its area() method returns Math.PI * this.radius * this.radius.
Starter code
// define the shape hierarchy
// Shape base class area() returns 0
// Circle subclass takes radius and computes areaSample solution
class Shape {
area() {
return 0;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
}Recall static members
Static members are independent of instances and called on the class name. A class can use static members to track the total count of instances, store shared constants, or provide helper methods.
In the final task you will add a static counter and a static describe method, so you see class-level data alongside instances.
Practice Logger class
Declare a Logger class. Add a static count property set to 0. Its constructor takes no parameters and increases Logger.count by one each call. Add a static describe() method that returns a string.
Starter code
// declare the Logger class
// add a class-level counter and a describe method
// constructor raises the counter on each instanceSample solution
class Logger {
static count = 0;
constructor() {
Logger.count++;
}
static describe() {
return "Logger instance";
}
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword declares a class-level member?
- const
- instance
- private
- static Correct answer
Explanation: static members belong to the class.
2 Match the concepts
| Term | Meaning |
|---|---|
class |
class declaration |
constructor |
initializer method |
extends |
subclass keyword |
super() |
parent constructor call |
static |
class-level member |