Gilbert Williams
Gilbert Williams

Reputation: 1050

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.

Upvotes: 4

Views: 95

Answers (2)

Oliver
Oliver

Reputation: 9002

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.

Upvotes: 3

Jamiec
Jamiec

Reputation: 136144

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.

Upvotes: 4

Related Questions