Interface vs Abstract Class

How to decide to use interface or abstract class ?
I see people say interface for contract, and abstract class is just an unreal class. But, I think abstract class is also a contract.
Is it better just using interface since abstract class hurts performance more ?
Which one is better between those two below :

class Post implements PostInterface, Entities


class Post extends AbstractEntities implements PostInterface

The practical realities of the two are:

  • Interfaces are strictly contract-only, no implementation, but your class can implement any number of them.
  • Abstract classes can specify a contract and implementation, but your class can extend from only one.

So if you need to inherit some implementation, then an abstract class may be what you need, but if it’s pure contract, then make it an interface.


A couple other tips.

Inheritance is often over-used. If possible, try to use other objects rather than inheriting from them (favor composition over inheritance).

Also, having a Post interface is useful only if you plan on having many different kinds of Post classes (e.g., SimplePost, ComplexPost, LazyPost, whatever) so that you can handle them all the same through their common interface.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.