-5

I was wondering what the difference is between aan interface and an abstract class? What are the pros/cons and when should I use what?

Next to those questions, can I still do Dependency Injection with an abstract class? Since I'm using DI and want to declare static fields / private methods

Tom Kerkhove
  • 2,151
  • 5
  • 26
  • 42

2 Answers2

5

An interface cannot have an implementation.

Abstract classes can have implementation - this can be used by the inheriting/implementing types.

Use abstract classes when you want to share the implementation between the inheriting types, to allow for code reuse (and keep DRY).

Additionally, a class can implement any number of interfaces, but can only inherit from a single class, so this is another consideration.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Also worth mentioning is that a class/interface can implement/extend multiple interfaces, but a class can extend only one abstract class. – TheBuzzSaw Feb 22 '13 at 14:41
  • @TheBuzzSaw - Good point. Answre updated. – Oded Feb 22 '13 at 14:42
  • Thanks, I updated my question. So I can declare my private/static fields & methods in an abstract class an my public classes in an interface? – Tom Kerkhove Feb 22 '13 at 14:44
  • @HellScream - You can do DI with abstract classes, yes. You can pretty much do anything in an abstract class that you can with a normal class, except instantiate it. – Oded Feb 22 '13 at 14:45
  • So abstracts are mainly for DRY and interface just as a "contract", thanks! – Tom Kerkhove Feb 22 '13 at 14:55
0

One difference is that Abstract classes can contain implemented members, while interface members dont have any implementation/

Another is that interfaces can't have fields, Abstract classes can.

Abstract classes encourage reusing base code for classes that inherit it, while interfaces create compatibility between classes that implement the same interfaces.

As stated first above, you can implement multiple interfaces, but you can only inherit from one class.

Freeman
  • 5,691
  • 3
  • 29
  • 41