Abstract Classes
Abstract classes provide a blueprint for other classes, defining methods that must be implemented by derived classes.
Abstract Classes
Output
Click Run to execute your code
Abstract Class Rules:
- Cannot be instantiated directly
- Can have abstract methods (no implementation)
- Can have concrete methods (with implementation)
- Child classes MUST implement abstract methods
Abstract vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Can have implementation | ✓ Yes | ✗ No |
| Can be instantiated | ✗ No | ✗ No |
| Multiple inheritance | ✗ No | ✓ Yes |
| Constructor | ✓ Yes | ✗ No |
| Use case | Shared behavior + contract | Pure contract |
Common Mistakes
1. Trying to Instantiate Abstract Class
abstract class Shape {
abstract getArea(): number;
}
let shape = new Shape(); // ✗ Error!
// ✓ Create concrete child class
class Circle extends Shape {
getArea() { return 0; }
}
let circle = new Circle(); // ✓ OK
2. Not Implementing Abstract Methods
abstract class Animal {
abstract makeSound(): void;
}
class Dog extends Animal {
// ✗ Error - must implement makeSound()
}
// ✓ Correct
class Dog extends Animal {
makeSound() { console.log("Woof"); }
}
When to Use: Use abstract classes when you
have shared implementation AND want to enforce a contract.
Summary
- Abstract classes combine interfaces and base classes
- Cannot instantiate abstract classes
- Child classes must implement abstract methods
- Can have both abstract and concrete members
Enjoying these tutorials?