Subclass

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Inheritance (extends)

JS · Classes & OOP
Syntax
class Child extends Parent {
  constructor(params) {
    super(parentParams);
  }
}
Example
class Shape {
  constructor(color) {
    this.color = color;
  }
  describe() {
    return `A ${this.color} shape`;
  }
}

class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }
  get area() {
    return Math.PI * this.radius ** 2;
  }
  describe() {
    return `A ${this.color} circle (r=${this.radius})`;
  }
}

const c = new Circle("blue", 5);
console.log(c.describe());
console.log(c.area.toFixed(2));
Output
"A blue circle (r=5)"
"78.54"

Note super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.

PYPython

Inheritance & super()

PY · Classes & OOP
Syntax
class Child(Parent):
    def __init__(self):
        super().__init__()
Example
class Vehicle:
    def __init__(self, make: str, year: int):
        self.make = make
        self.year = year

class ElectricCar(Vehicle):
    def __init__(self, make: str, year: int, range_km: int):
        super().__init__(make, year)
        self.range_km = range_km

    def __repr__(self) -> str:
        return f"{self.year} {self.make} ({self.range_km}km range)"

car = ElectricCar("Tesla", 2026, 600)
print(car)
Output
2026 Tesla (600km range)

Note Always call super().__init__() in the child to ensure the parent is properly initialized. Python supports multiple inheritance via MRO (Method Resolution Order).

Frequently asked questions

How does JavaScript handle subclass?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Inheritance (extends)" snippet in JavaScript uses `class Child extends Parent {`.
Which code does the JavaScript example use?
The "Inheritance (extends)" snippet uses `class Child extends Parent {`, from the Classes & OOP section of the JavaScript cheat sheet.
Which stacks cover "subclass" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Inheritance (extends)": super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.