Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use interface and abstract over just abstract?

I'm reading some code online where someone implemented the following classes: IMapObj which is a normal interface, AbstractMapObj that derives from that interface and a lot of map objects that derive from AbstrsctMapObj.

Throughout all his code, he refers to IMapObj and not AbstractMapObj.

What's the benefit of using an interface and an abstract class instead of just an abstract class? Needless to say no other class derives from IMapObj, only AbstractMapObj.

like image 334
Gilbert Williams Avatar asked Mar 02 '23 15:03

Gilbert Williams


2 Answers

There is only 1 reason to use both, and that is that the abstract class can provide a default implementation of some or all of the functionality. The interface can be easily mocked for testing.

like image 179
Jamiec Avatar answered Mar 12 '23 18:03

Jamiec


What's the benefit of using an interface and an abstract class instead of just an abstract class?

In the example posted, there appears to be no real reason to use an abstract class. In other scenarios, the abstract class could provide a common base to a subset of the interface implementations. With the interface providing a more stable/common abstraction for the rest of the application/library.


Generally I would only use an abstract class to share a common implementation, not as an interface definition - but that's just my preference. There are many different styles and patterns that people use.

like image 27
Oliver Avatar answered Mar 12 '23 17:03

Oliver