Archive for the 'Software Development Job Search' Category

Abstract Classes Versus Interfaces

Tuesday, January 17th, 2012

Had a very interesting question on a recent interview: “What’s the difference between an abstract class and an interface? Why would you choose to use one over another?”

How exactly do you answer this question off the top of your head in an interview format and truly do the subject justice? I simply had to hope that the interviewer was more interested in thought processes and an abstract discussion than concrete information.

After having time to fully digest the question and put my thoughts together, here is my attempt at an intelligent answer, which may not be much better than my interview answer.

My biggest problem with this question is that it pre-supposes that the two are interchangeable. While an argument can be made that it is possible to use them interchangeably, it ignores their strengths, weaknesses and design purposes.

Abstract Class:
Full or Partial implementation
Inheriting classes may only inherit from one class
Updates passed along to inheriting classes
Great for classes that are similar (Dog and Cat both inherit from Animal)

Interfaces:
Only define input/output contract, no implementation
Classes may implement multiple interfaces
Once defined, should never change
Great for functionality used in many dis-similar classes

This still doesn’t quite answer the question, another good way to look at it is Nouns versus Verbs. Abstract Classes represent a Noun, such as in the example given above of Dog and Cat inheriting from Animal, while interfaces represent a Verb. If I were representing my dog Heidi as a class, she would inherit from Dog, but would need to implement the interfaces IJumpOnEveryone and IChewOnYourHand.

But in the end, I’m not sure we’ll come to a conclusion of what’s “right” and what’s “wrong” in this. While their are the obvious cases that neatly fit into either/or, as always I hate the cases where I can make a valid argument for either way. It’s times like those where I hope that one presents a clear disadvantage over the other to help me select.

I’d love to hear others opinions on this, please comment.