Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does abstract class have to implement all methods from interface?

Tags:

   interface BaseInter{       name : string;       test();     }      abstract  class Abs implements  baseInter{     } 

In TypeScript, compiler complaints that the class incorrectly implements the interface:

name is missing in type abs.

Here Absis an abstract class and so why do we need to implement the interface over there?

like image 535
Jerin Joseph Avatar asked Jun 16 '17 16:06

Jerin Joseph


People also ask

Does abstract class have to implement all interface methods?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.

Why are all methods in a Java interface abstract?

Abstract methods do not have the body they only have declaration but no definition. The definition is defined by implementing classes. So we look at all the examples where a method can exist with its behavior (body) inside the interface.

What will happen if an implementing class does not implement all abstract methods of an interface?

If you don't implement all methods of your interface, than you destroy the entire purpose of an interface. Show activity on this post.

What happens if I will not provide an abstract method in abstract class and interface?

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract.


2 Answers

You need to re-write all of the members/methods in the interface and add the abstract keyword to them, so in your case:

interface baseInter {     name: string;     test(); }  abstract class abs implements baseInter {     abstract name: string;     abstract test(); } 

(code in playground)

There was a suggestion for it: Missing property declaration in abstract class implementing interfaces but it was declined for this reason:

Although, the convenience of not writing the declaration would be nice, the possible confusion/complexity arising from this change would not warrant it. by examine the declaration, it is not clear which members appear on the type, is it all properties, methods, or properties with call signatures; would they be considered abstract? optional?

like image 179
Nitzan Tomer Avatar answered Sep 28 '22 17:09

Nitzan Tomer


You can get what you want with a slight trick that defeats the compile-time errors:

interface baseInter {     name : string;     test(); }  interface abs extends baseInter {}  abstract class abs implements baseInter{ } 

This trick takes advantage of Typescript's Declaration Merging, and was originally presented here and posted on a related SO question here.

like image 38
Design.Garden Avatar answered Sep 28 '22 19:09

Design.Garden