1. Introduction
In TypeScript, both abstract classes and interfaces are used for designing blueprints for other classes, but they serve different purposes. An abstract class is a base class that cannot be instantiated and can include implementation details for its members. An interface, however, is a purely structural contract - it contains no implementation details but defines the syntax that any class must adhere to.
2. Key Points
1. Implementation: Abstract classes can contain implementation details, but interfaces cannot.
2. Instantiation: Abstract classes cannot be instantiated directly, interfaces are never instantiated.
3. Methods: Abstract classes can have both abstract and concrete methods, and interfaces can only have abstract methods (no implementation).
4. Extension: Abstract classes can be extended, and interfaces can be extended and implemented.
3. Differences
Characteristic | Abstract Class | Interface |
---|---|---|
Implementation | Can contain implementation | Cannot contain implementation |
Instantiation | Cannot be instantiated directly | Never instantiated |
Methods | Abstract and concrete methods | Only abstract methods |
Extension | Can be extended | Can be extended and implemented |
4. Example
// Example of an Abstract Class
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('Moving along!');
}
}
// Example of an Interface
interface Movable {
move(): void;
}
// Implementing an Interface
class Car implements Movable {
move(): void {
console.log('Driving along!');
}
}
Output:
Abstract Class Output: Cannot be instantiated, but can define both abstract and concrete methods. Interface Output: Defines a contract for classes, no implementation included.
Explanation:
1. The Animal abstract class includes an abstract method makeSound and a concrete method move.
2. The Movable interface only defines the contract for a move method, which the Car class then implements.
5. When to use?
- Use an abstract class when you need to define a base class with some shared implementation that other classes should inherit from.
- Use an interface when you need to enforce a specific contract or shape for classes without concerning yourself with implementation details.
Comments
Post a Comment
Leave Comment