4 min read
•Question 22 of 48mediumWhat is the difference between implements and extends?
Class inheritance vs interface implementation.
What You'll Learn
- extends for inheritance
- implements for interfaces
- When to use each
extends (Inheritance)
code.tsTypeScript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(): void {
console.log(`${this.name} is moving`);
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name); // Call parent constructor
this.breed = breed;
}
bark(): void {
console.log("Woof!");
}
}implements (Interface)
code.tsTypeScript
interface Printable {
print(): void;
}
interface Loggable {
log(message: string): void;
}
// Can implement multiple interfaces
class Document implements Printable, Loggable {
print(): void {
console.log("Printing...");
}
log(message: string): void {
console.log(message);
}
}Key Differences
| extends | implements |
|---|---|
| Inherits implementation | Must provide implementation |
| Single inheritance only | Multiple interfaces allowed |
| For classes | For interfaces |