CodeBlanks Logo Icon CodeBlanks

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.

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

script.js
// define the shape hierarchy
// Shape base class area() returns 0
// Circle subclass takes radius and computes area

Sample solution

script.js
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

script.js
// declare the Logger class
// add a class-level counter and a describe method
// constructor raises the counter on each instance

Sample solution

script.js
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

All lessons in Advanced