Declare methods in abstract classes that subclasses must implement.
Abstract methods are method signatures declared within an abstract class using the abstract keyword. They define a method's name, parameters, and return type without providing an implementation. Any non-abstract class that extends the abstract class must provide a concrete implementation of every abstract method.
Abstract methods establish a contract between a base class and its subclasses, ensuring that all subclasses provide specific behavior while allowing the base class to define shared logic in its concrete methods. This is a key pattern for the Template Method design pattern, where the base class defines an algorithm's skeleton and delegates specific steps to subclasses.
Unlike interface methods, abstract methods exist within a class that can also contain concrete methods with full implementations. This allows you to mix shared functionality with required overrides in a single inheritance hierarchy. Abstract methods can have any access modifier except private, as private members cannot be overridden by subclasses.
abstract class Shape {
abstract area(): number;
abstract perimeter(): number;
describe(): string {
return `Area: ${this.area()}, Perimeter: ${this.perimeter()}`;
}
}
class Circle extends Shape {
constructor(private radius: number) { super(); }
area() { return Math.PI * this.radius ** 2; }
perimeter() { return 2 * Math.PI * this.radius; }
}
const c = new Circle(5);
c.describe(); // 'Area: 78.54, Perimeter: 31.42'