How do you decide between using an Abstract Class and an Interface?

Brian Hodge picture Brian Hodge · Feb 17, 2009 · Viewed 20.1k times · Source

Duplicate: Interface vs Base class


I have been getting deeper into the world of OOP, design patterns, and actionscript 3 and I am still curious how to know when to use an Abstract class (pseudo for AS3 which doesn't support Abstract classes) and an interface. To me both just serve as templates that make sure certain methods are implemented in a given class. Is the difference solely in the fact that Abstract classes require inheritance and an Interface merely extends?

Thanks, Brian Hodge hodgedev.com

Answer

Mark Rogers picture Mark Rogers · Feb 17, 2009

Use an abstract class if you have some functionality that you want it's subclasses to have. For instance, if you have a set of functions that you want all of the base abstract class's subclasses to have.

Use an interface if you just want a general contract on behavior/functionality. If you have a function or object that you want to take in a set of different objects, use an interface. Then you can change out the object that is passed in, without changing the method or object that is taking it.

Interfaces are typically loose, compared to Abstract classes. You wouldn't want to use interfaces in a situation where you are constantly writing the same code for all of the interface's methods. Use an abstract class and define each method once.

Also, if you are trying to create a specific object inheritance hierarchy, you really wouldn't want to try to do that with just interfaces.

Also, again, in some languages you can only have a single base class, and if an object already has a base class, you are going to have to do some refactoring in order to use an abstract base class. This may or may not mean that you might want to use an inteface instead.

As @tvanfosson notes, it's not a bad idea to use a lot of interfaces, when you really understand abstract classes and interfaces, it's not really an either/or situation. A particular situation could use both abstract classes and interfaces or neither. I like to use interfaces sometimes simply to restrict what a method or object can access on a passed in parameter object.