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?