Abstract Classes & Methods
Create strict blueprints for subclasses.
The Blueprint
An abstract class is a base class that cannot be instantiated directly. It exists solely to be extended by other classes.
Inside an abstract class, you can define abstract methods. These are method signatures without an implementation. Any subclass *must* provide the actual implementation for these methods.
Forced Contracts
If you are building a game with different types of Enemies, they might all share some common logic (like health and a takeDamage method).
But how they attack should be unique to each enemy. By making the base Enemy class abstract, and giving it an abstract attack() method, you force every specific enemy subclass to define its own attack behavior, while safely sharing the health logic.
Syntax
typescript
abstract class Animal {
// Shared implementation
move() { console.log("Moving"); }
// Required blueprint
abstract makeSound(): void;
}
// Error! Cannot create an instance of an abstract class.
// const a = new Animal();
class Dog extends Animal {
// Must implement this!
makeSound() { console.log("Woof!"); }
}
Try it
Watch the compiler enforce the rules. Try instantiating the abstract base class directly, and see what happens when the subclass forgets to implement the required method.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Abstract classes cannot be instantiated with
new. - Abstract methods have no body and MUST be implemented by subclasses.
- They are perfect for sharing common logic while forcing specific custom behavior in subclasses.
- Use interfaces when there is no shared logic at all.
Done with this concept?
Mark it complete to track your progress. No login needed.