Norton
Norton

Reputation: 29

The difference between Interface and Abstract class (JS)

The limitation of an abstract class lies in the fact that a sub-class can only extend a single abstract class. Hence, multiple inheritance is found in Interfaces.

Interfaces can have conrete methods just like abstract classes, but cannot have instance fields, only public, static, final fields.

Am I correct when i conclude that the only difference lies in the fact that interfaces simply cannot have instance fields?

Upvotes: 2

Views: 14569

Answers (3)

RichardPlangar
RichardPlangar

Reputation: 41

I assume your question pertains to Typescript because "interface" and "abstract" declarations can only be used in Typescript.

Your conclusion is correct, however there are more than just one difference between them:

  • An interface can have only abstract methods, an abstract class can have both abstract and non-abstract methods
  • An interface can only have public members, while an abstract class can have protected and public members.
  • Abstract class can provide the implementation of the interface. Interface can not provide the implementation of an abstract class

If you would like to dive deeper in the topic in terms of design (still related to interface and abstract class) I would recommend the "composition over inheritance" principle.

Here: Prefer composition over inheritance?

Here: https://en.wikipedia.org/wiki/Composition_over_inheritance

Upvotes: 1

adz5A
adz5A

Reputation: 2032

interface is often some kind of type declaration, whereas class or abstract class are class declaration, which in JS are just constructors, though they often define a specific "type" of values. abstract are a special case in between the two because they define a new concrete value (a constructor in JS) but cannot be instantiated without being subclassed.

Bottom line, interfaces are declaration in the space of types, whereas [abstract] class are declaration in the space of values. In typescript for instance you can bridge the two using class implements. In JavaScript the term interface more often refers to the general shape of behaviour of a specific type of value returned by some API (see https://developer.mozilla.org/en-US/docs/Web/API/Event where the term interface is used to describe different kind of events).

Upvotes: 2

Bogdan Surai
Bogdan Surai

Reputation: 1275

Interfaces only describe what properties and methods should be implemented, and don’t describe how methods should work.

But abstract classes may describe how a method works, like in regular classes. For example:

abstract class MyClass {
   abstract method_1() // a method with no implementation

   method_2() { // a method with implementation
      // do something
   }
}

Interfaces look like:

interface MyInterface {
   method_1(): void;
   method_2(): string;
}

Upvotes: 2

Related Questions