259

I would like to know what Man and Child have in common and how they differ.

class Person {
  name: string;
  age: number;
}
class Child extends Person {}
class Man implements Person {}
BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
davejoem
  • 4,902
  • 4
  • 22
  • 31
  • 3
    Nicely explained here : https://stackoverflow.com/a/35990799/452213 . Especially, the example : http://www.typescriptlang.org/play/#src=abstract%20class%20A%20%7B%0A%20%20%20%20abstract%20m()%3A%20void%3B%0A%09otherM()%20%7B%0A%09%09console.log(%22otherm%22)%3B%0A%09%7D%0A%7D%0A%0Aclass%20B%20extends%20A%20%7B%0A%20%20%20%20m()%3A%20void%20%7B%20%7D%0A%7D%0A%0Aclass%20C%20implements%20A%20%7B%0A%20%20%20%20m()%3A%20void%20%7B%20%7D%0A%7D – sudip Aug 17 '18 at 23:01

7 Answers7

342

Short version

  • extends means:

The new class is a child. It gets benefits coming with inheritance. It has all the properties and methods of its parent. It can override some of these and implement new ones, but the parent stuff is already included.

  • implements means:

The new class can be treated as the same "shape", but it is not a child. It could be passed to any method where Person is required, regardless of having a different parent than Person.

More ...

In OOP (languages like C# or Java) we would use

extends to profit from inheritance.

... Inheritance in most class-based object-oriented languages is a mechanism in which one object acquires all the properties and behaviours of the parent object. Inheritance allows programmers to: create classes that are built upon existing classes ...

implements will be more for polymorphism.

... polymorphism is the provision of a single interface to entities of different types...

So we can have a completely different inheritance tree for our class Man:

class Man extends Human ...

but if we also declare that Man can pretend to be the Person type:

class Man extends Human 
          implements Person ...

...then we can use it anywhere Person is required. We just have to fulfil Person's "interface" (i.e. implement all its public stuff).

implement other class? That is really cool stuff

Javascript's nice face (one of the benefits) is built-in support for duck typing.

"If it walks like a duck and it quacks like a duck, then it must be a duck."

So, in Javascript, if two different objects have one similar method (e.g. render()) they can be passed to a function which expects it:

function(engine){
  engine.render() // any type implementing render() can be passed
}

To not lose that in Typescript, we can do the same with more typed support. And that is where

class implements class

has its role, where it makes sense.

In OOP languages as C#, no way to do that.

The documentation should help here:

Interfaces Extending Classes

When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. This means that when you create an interface that extends a class with private or protected members, that interface type can only be implemented by that class or a subclass of it.

This is useful when you have a large inheritance hierarchy, but want to specify that your code works with only subclasses that have certain properties. The subclasses don’t have to be related besides inheriting from the base class. For example:

class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Button extends Control implements SelectableControl {
    select() { }
}

class TextBox extends Control {
    select() { }
}

// Error: Property 'state' is missing in type 'Image'.
class Image implements SelectableControl {
    private state: any;
    select() { }
}

class Location {

}

So, while

  • extends means it gets all from its parent
  • implements in this case it's almost like implementing an interface. A child object can pretend that it is its parent... but it does not get any implementation.
Clonkex
  • 3,373
  • 7
  • 38
  • 55
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • when you say "`extends`-it gets all from its parent", does it apply to private members? For instance `class Person {private name: string} class man extends Person{gender: string;}` does `man` have the property name? – davejoem Aug 14 '16 at 05:59
  • Private are there as well. Just inaccessible by TS. Make them protected and you can use them. In case of "implements" just the public part makes sense. Hope it helps a bit – Radim Köhler Aug 14 '16 at 06:50
  • 2
    The actual error for Image is clearer. "Class 'Image' incorrectly implements interface SelectableControl. Types have separate declarations of a private property 'state'." Saying, "property state is missing" is confusing because it's not missing, it's duplicated. – strattonn Feb 02 '21 at 22:25
  • Honestly, I started to read this screed but then found the whole thing was summarised in a couple of sentences here: https://stackoverflow.com/questions/35990538/extending-vs-implementing-a-pure-abstract-class-in-typescript/35990799#35990799. "A new class can be treated as the same 'shape' while it is not a child." Say what? – see sharper Apr 22 '21 at 23:22
145

You have classes and interfaces in typescript (and some other OO languages).

An interface has no implementation; it's just a "contract" of what members/method this type has.

For example:

interface Point {
    x: number;
    y: number;
    distance(other: Point): number;
}

Instances that implement this Point interface must have two members of type number: x and y, and one method, distance, which receives another Point instance and returns a number.

The interface doesn't implement any of those.

Classes are the implementations:

class PointImplementation implements Point {
    public x: number;
    public y: number;
    
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
    
    public distance(other: Point): number {
        return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
    }
}

(code in playground)

In your example, you treat your Person class once as a class when you extend it and once as an interface when you implement it.

Your code:

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

class Child  extends Person {}

class Man implements Person {}

It has the following compilation error:

Class 'Man' incorrectly implements interface 'Person'. Property' name' is missing in type 'Man'.

And that's because interfaces lack implementation.
So if you implement a class, then you only take its "contract" without the implementation, so you'll need to do this:

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

(code in playground)

The bottom line is that you want to extend another class in most cases and not to implement it.

kohane15
  • 809
  • 12
  • 16
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
42

Extends VS implements

  • extends: The child class (which is extended) will inherit all the properties and methods of the class is extends
  • implements: The class which uses the implements keyword will need to implement all the properties and methods of the class which it implements

To put in simpler terms:

  • extends: Here you get all these methods/properties from the parent class so you don't have to implement this yourself
  • implements: Here is a contract which the class has to follow. The class has to implement at least the following methods/properties

Example:

class Person {
  name: string;
  age: number;

  walk(): void {
    console.log('Walking (person Class)')
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
class child extends Person { }

// Man has to implements at least all the properties
// and methods of the Person class
class man implements Person {
  name: string;
  age: number

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  walk(): void {
    console.log('Walking (man class)')
  }

}

(new child('Mike', 12)).walk();
// logs: Walking(person Class)

(new man('Tom', 12)).walk();
// logs: Walking(man class)

In the example we can observe that the child class inherits everything from Person whereas the man class has to implement everything from Person itself.

If we were to remove something from the man class for example the walk method we would get the following compile time error:

Class 'man' incorrectly implements class 'Person'. Did you mean to extend 'Person' and inherit its members as a subclass? Property 'walk' is missing in type 'man' but required in type 'Person'.(2720)

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
8

Great Answer from @nitzan-tomer! Helped me a lot... I extended his demo a bit with:

IPoint interface;
Point implements IPoint;
Point3D extends Point;

And how they behave in functions expecting an IPoint type.

So what I've learned so far and been using as a thumb-rule: If you're using classes and methods expecting generic types, use interfaces as the expected types. And make sure the parent or base-class uses that interface. That way you can use all subclasses in those as far as they implement the interface.

Here the extended demo

Sinandro
  • 2,426
  • 3
  • 21
  • 36
andzep
  • 1,877
  • 24
  • 35
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/18734440) – aronisstav Feb 06 '18 at 11:38
  • 1
    @aronisstav I only posted an extended demo of what I found a good answer that already helped me. But maybe someone else would find the work I did extending the demo useful. That's all. Comments are not really meant for putting a code-block, so that's why I find it better understandable in an Answer-Post. So what's the problem with it? – andzep Feb 07 '18 at 11:11
  • Your answer was (automatically?) flagged due to length and content, appeared in my review queue and I gave merit to the reasons presented in the flag. Its main contribution (explaining that you extended the demo) would be better as a comment. With the added paragraph perhaps it is indeed more useful. – aronisstav Feb 07 '18 at 13:01
  • @andzep your extended demo example is really helpful. – namit Nov 16 '18 at 06:40
6
  1. Interface extends interface with shape
  2. Interface extends class with shape
  3. Class implements interface should implements all fields provided by the interface
  4. Class implements class with shape
  5. Class extends class with all fields

extends focus on inherit and implements focus on constraint whether interfaces or classes.

lei li
  • 1,244
  • 1
  • 12
  • 35
6

Basically:

  • extends will get all properties and methods of the parent class.
  • implements will obligate us to implement all of the properties and methods defined in the interface.
Pouya Jabbarisani
  • 1,084
  • 3
  • 16
  • 29
  • OKay but why? Why do we need extends when 99% of people are saying inheritance is error prone and to program to an interface instead? Can you explain? – Isaac Pak Mar 30 '22 at 12:45
0

Interfaces help reduce coupling between classes by providing a contract or common language that defines how different classes can interact with each other, allowing for loose coupling and promoting easier maintenance and extensibility (Programming to an interface). By using interfaces instead of inheritance, the dependencies between classes are minimized, leading to a reduction in code coupling. This decoupling enhances code reusability, testability, and overall system flexibility.

Sadek Mehri
  • 50
  • 1
  • 5
  • 2
    did you get this from chatgpt? – starball Jul 06 '23 at 10:47
  • Don't worry, sir. I'm a software engineer and a blogger at the same time. I've already read your terms and conditions, and I am not inclined to disrupt this community. I have informed the owner of the article about the exact differences in theory. I didn't make an example to make it more clear. He should know this term (programming to an interface). because by using extend keyword the parent object is called first then the child code and maybe this alternatives is unnecessary to make the job done. – Sadek Mehri Jul 06 '23 at 12:11
  • what article are you referring to? – starball Jul 06 '23 at 19:55
  • https://www.baeldung.com/cs/program-to-interface – Sadek Mehri Jul 06 '23 at 23:56
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 08 '23 at 08:00