Abstract class

2 snippets across 2 stacks — Python, TypeScript

PYPython

Abstract Base Classes

PY · Classes & OOP
syntax
from abc import ABC, abstractmethod
class Base(ABC):
    @abstractmethod
    def method(self): ...
example
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

# shape = Shape()  # TypeError: can't instantiate abstract class
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
output
Area: 78.54

Note Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.

TSTypeScript

Abstract Classes

TS · Classes
syntax
abstract class Name {
  abstract method(): Type;
  concreteMethod(): Type { ... }
}
example
abstract class Shape {
  abstract area(): number;
  abstract perimeter(): number;

  describe(): string {
    return `Area: ${this.area().toFixed(2)}, Perimeter: ${this.perimeter().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }

  perimeter(): number {
    return 2 * Math.PI * this.radius;
  }
}

// const shape = new Shape(); // Error: Cannot instantiate abstract class
const circle = new Circle(5);
console.log(circle.describe());
output
// "Area: 78.54, Perimeter: 31.42"

Note Abstract classes cannot be instantiated directly. They can contain both abstract members (no implementation — subclasses must provide them) and concrete members (shared implementation). Use abstract classes when subclasses share behavior; use interfaces when they only share shape.