implements
- TypeScript course
- Intermediate
- Lesson 63/89
- 4 min
Learn to implement an interface with a class.
What is implements?
The implements keyword declares that a class implements an interface. The interface forms a contract for the class; the class must contain all members of the interface. The interface provides only signatures; the implementation belongs to the class.
interface Drivable {
drive(): void;
}
class Car implements Drivable {
drive() { console.log("vroom"); }
}Implementing multiple interfaces
A class can implement multiple interfaces; they are separated by commas. All members of all interfaces must be present in the class. Unlike extends, which is limited to single inheritance, this allows multiple contracts.
interface Walkable { walk(): void; }
interface Flyable { fly(): void; }
class Bird implements Walkable, Flyable {
walk() {}
fly() {}
}Practice Implement the SesCikariran class
Define interface SesCikariran with sesCikar(): void inside. Then make the Kedi class implement this interface and have sesCikar print "miyav". Put a console.log inside the method and call new Kedi().sesCikar().
Starter code
// SesCikariran adinda interface tanimla
// sesCikar(): void imzasi olsun
// Kedi sinifi bu interface'i uygulasin
// sesCikar "miyav" yazsin
// new Kedi().sesCikar() ile çağırSample solution
interface SesCikariran {
sesCikar(): void;
}
class Kedi implements SesCikariran {
sesCikar() { console.log("miyav"); }
}
new Kedi().sesCikar();Expected output
miyav
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What must a class using implements do?
- Must implement all members of the interface Correct answer
- Must implement only one member
- Must extend the interface
- Must mark the interface as abstract
Explanation: implements establishes a contract between the class and the interface; the class must contain all members of the interface.
2 Keyword to implement an interface
class Araba ____ Surulebilir { sur() {} }
class Araba implements Surulebilir { sur() {} }
Explanation: The `implements` keyword is used to declare that a class implements an interface.
3 implements concepts
| Term | Meaning |
|---|---|
implements |
Applies the interface contract |
interface |
Contains only signatures |
sözleşme |
Makes members mandatory |
virgül |
Separates multiple interfaces |