What is the difference between extends and implements ?

class Media {
  format: string;
}
class Video extends Media {}
class Image implements Media {}

To put in simpler terms:

extends: The class get all these methods and properties from the parent, so you don’t have to implement.

implements: The class has to implement methods and properties.

other said :

  • extends means:

The new class is a child. It gets benefits coming with inheritance. It has all properties, methods as its parent. It can override some of these and implement new, but the parent stuff is already included. The child class (which is extended) will inherit all the properties and methods of the class it extends

  • implements means:

The new class can be treated as the same “shape”, while it is not a child : The class which uses the implements keyword will need to implement all the properties and methods of the class which it implements

Example

Let´s observe this short line of code

class Person {
    name: string;
    age: number;
}
class Child  extends Person {}

class Man implements Person {}

When transpiling, we will have a compilation error saying:

Class ‘Man’ incorrectly implements interface ‘Person’.

Property ‘name’ is missing in type ‘Man’.

And that’s because interfaces lack implementation.
So When we implement a class then we only take its “contract” without the implementation. In the current example, to fix the issues, we need to do this :

class Man implements Person {
    name: string;
    age: number;
}

Bottom line is that in most cases we will want to extend another class and not to implement it.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *