JavaScript
Summary - Classes
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
constructor initializes a new instance; you create one with new. - Methods reach the instance through
this. extends creates a subclass; super() calls the parent constructor.static members belong to the class.
Now let us build a hierarchy that brings these together.
Exercise 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.
Show example solution
First Shape with area(), then in Circle extends Shape call super() and set this.radius.
Example 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.
Exercise 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.
Show example solution
Start with static count = 0, in the constructor do Logger.count++, finally add static describe().
Example solution:
class Logger {
static count = 0;
constructor() {
Logger.count++;
}
static describe() {
return "Logger instance";
}
}
Test yourself
-
Which keyword declares a class-level member?
- static
- instance
- private
- const
Show answer
static — Correct! static members belong to the class.
-
Match the concepts
- class
- class declaration
- constructor
- initializer method
- extends
- subclass keyword
- super()
- parent constructor call
- static
- class-level member
Next lesson: What is a prototype?