Home > Best Practices, Learn This, Opinion, tutorial > Learn This: When to use an Abstract Class and an Interface

Learn This: When to use an Abstract Class and an Interface

February 12th, 2009

For some odd reason, work allows me to handle phone screens and interviews. Each time I give an interview, I try to do three things. First I ask them about general programming questions. This might be OO questions. It might be methodology questions. It might be design pattern questions. Next I like to ask them more specific technologies questions, such as questions “how do you do ABC in Flex? Java?”. Lastly I want to know what they do in their spare time. What books they read? Do they code outside of work? How they go about researching new technologies? Etc.

However, the place I find people getting stuck are basic/general programming knowledge. Recently I conducted an interview, and this person just missed every question I asked. I don’t mind if people miss questions. Sometimes, it just takes some leading and they will get the correct answer. There are certain things though that if you miss entirely, then we have a problem. This has inspired me for this new section that I would like to call “Learn This”. These are topics that I find rather important for a potential candidate to know. There are a few past articles I could think about putting into this section, but I will start fresh.

Abstract Class vs an Interface.

I normally used this “What is the difference between an Abstract Class and an Interface” as a quick way to gauge someone. Lots of times, its the first or second question I will ask. I cannot tell you how many times people will mess this question up. 9 times out of 10, people read about it at some www.basicinterviewquestions.com (not a real site hehe), giving the canned response of “You can define default functionality in an abstract class and you can just define functions in an interface”. The curve ball is thrown when you ask “Why would you use one over the other?”. That will earn you the ‘deer in headlights’ look. The other 1 out of 10 you will get a “I never had to use that so I don’t know”.

At the top level, the are a few basic difference. Abstract classes allow for default default function definition. This means that whatever class extends the abstract class will have access to this. If we have a base class where all the classes will perform the same function, then we can define that in our Abstract class. An interface is a list of functions or properties that if a class implements it, it will have to have those functions defined within it. It is a situation of “Is-A” vs “Can-Do-this”. Objects that extends an Abstract class “Is-A” base class. Objects that implement “Can-Do-This”. Now if I asked this question and got the answer, yes, that would be the correct answer. However, I want to know why one would want to use an interface over an abstract class, and vice versa.

When to prefer an interface

Back when I wrote about the importance of composition, I mentioned that it is extremely useful when you don’t want a massive hierarchical type framework. The same applies to interfaces. This isn’t my example, but its the best one Ive come across. Lets say you have an interface for a Director and another interface for a Actor.

public interface Actor{
   Performance say(Line l);
}
public interface Director{
   Movie direct(boolean goodmovie);
}

In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:

public interface ActorDirector extends Actor, Director{
...
}

We could achieve the same thing using abstract classes. Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.

When to prefer an Abstract class

Abstract classes allow you to provide default functionality for the subclasses. Common knowledge at this point. Why is this extremely important though? If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.

Speaking from personal experiences, frameworks is a good place to show when and where to use both an abstract class and an interface. Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class. An example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.

public interface BusinessRule{
   Boolean analyze(Object o);
}

This can be used ANYWHERE. It can be used to verify the state of your application. Verify data is correct. Verify that the user is logged in. Each one of these classes just needs to implement the analyze function, which will be different for each rule.

Where as if we were creating a generic List object, the use of abstract classes would be better. Every single List object is going to display the data in a list in some form or another. The base functionality would be to have it go through its dataprovider and build that list. If we want to change that List object, we just extend it, override our build list function, change what we want and call super.buildList();

Almost everyone knows that interfaces means you are just defining a list of functions and that abstract classes has the option of providing default functionality. The snags come when you drop the ‘why would I use one over the other?’. Abstract classes and interfaces are some of the most important fundamentals of object oriented programming. Just knowing the differences between the two is not enough. When you can look at a situation and make a strong recommendation, you will known you have a much stronger knowledge of object oriented programming. Also it helps during interviews. :P .

Feel I left something out? Disagree? Leave a comment :) .

Marcel Best Practices, Learn This, Opinion, tutorial , , ,

  1. February 12th, 2009 at 11:59 | #1

    Regardless of the question asked, I would absolutely agree that I much prefer to use something that requires a discussion rather than a sound bite.

    I’ve often found questions such as Abstract Class vs Interface easily sets apart candidates, especially when you throw in other discussion points. But how about in situation X, would your change your answer given consideration Y. It’s pretty impossible to repeat this parrot fashion, you have to display some real knowledge and understanding to give a decent answer.

  2. February 12th, 2009 at 12:04 | #2

    I think you need to touch on decoupling and encapsulation and the role that interfaces and abstract classes play as part of this discussion.

    >> 9 times out of 10, people read about it it at some
    >> http://www.basicinterviewquestions.com,
    >> giving the canned response of “You can define
    >> default functionality in an abstract class and you
    >> can just define functions in an interface”.

    Don’t you just wanna say, “duh, tell me more”.

  3. admin
    February 12th, 2009 at 12:09 | #3

    I really want to start an series called “Learn This” and going over the importance of decoupling and encapsulation was one of the topics I have lined up. Good suggestions though! :)

  4. February 12th, 2009 at 12:20 | #4

    Good discussion here. I love asking this as an interview question, and I find the “IS-A” versus “CAN-DO” is a good start of an answer. I also frequently hear “the interface is a contract” and “you should program to an interface”. But people only really prove that they know what they’re talking about when you force them to give an example – b/c how you code the problem set really depends on the problem you’re trying to solve.

    For instance, if all you have are a bunch of flying birds, you could probably get by with just an Bird class with Cardinal, Robin, etc subclasses. But if you have flightless birds as well as flying birds – or if you’re talking about birds AND planes – then you’ll probably want an IFly interface. If you’re talking about something like Actionscript, the candidate should get into a discussion about limits on extension but not interface implementation, etc.

    As Mike said above, there are so many boilerplate answers to OO questions out there. The difference between a good candidate and a mediocre one is how willing they are to get into the weeds with examples.

  5. Shaun
    February 12th, 2009 at 16:06 | #5

    In 13 years of professional development I’ve never once heard someone refer to Interface & Abstract classes as an either / or proposition. Usually, the abstract base class will provide the default implementation of an interface if/where applicable. Your subclasses will refine or redefine as needed.
    Ever stop to think that may be why you get the deer in the headlights look?

  6. admin
    February 12th, 2009 at 16:17 | #6

    Shaun:

    Sorry if the article came across as something that stated they were mutually exclusive of each other. Of course you can use them together just fine. However, I still feel it is important to ask someone why they would use them in specific situations over the other one. If there wasn’t not a difference, then you might as well toss one out.

    Marcel

  7. February 12th, 2009 at 16:23 | #7

    In interviews, I start with a basic bit-shifting exercise and follow it up with asking if they know what a cron job is. Whether they answer correctly or not is beside the fact…cause we’ll probably end up hiring them regardless of my thumbs down.

  8. Rahul Garg
    February 13th, 2009 at 02:38 | #8

    hi there is some problem with ur rss feed plz resolve it ,it is a gr8 blog want to read it on feeds

  9. funkyboy
    February 13th, 2009 at 05:21 | #9

    Shouldn’t there be an “implements” instead of “extends” in this piece of code?

    public interface ActorDirector extends Actor, Director{

    }

  10. admin
    February 13th, 2009 at 08:48 | #10

    @funkyboy:

    You definitely made me second guess myself, so I decided to do a little research. According to the http://en.wikipedia.org/wiki/Interface_(Java), the syntax for interfaces is as follows:

    [visibility] interface InterfaceName [extends other interfaces] {
    constant declarations
    member type declarations
    abstract method declarations
    }

    Also, if you whip up a quick example in eclipse, you should get this error if you switch it to implements:

    Description Resource Path Location Type
    Syntax error on token “implements”, extends expected ActorDirector.java Spring/src/com/codeofdoom/dao line 3 Java Problem

    Hope that helps!

  11. admin
    February 13th, 2009 at 11:12 | #11

    Rahul Garg:

    I loaded it up in google reader and it seems fine. Here is the link if you arent using the correct one:

    http://feeds2.feedburner.com/CodeOfDoom

  12. Andrew Deakins
    March 10th, 2009 at 08:38 | #12

    you also forgot to mention that using interfaces also benefits when using dependency injection for mocking frameworks….

    just thought i’d add my 2 cents

  13. April 21st, 2009 at 13:32 | #13

    Hello, I can’t understand how to add your blog in my rss reader.plz tell me thank you.

  14. April 21st, 2009 at 13:57 | #14

    @sears parts
    i use google reader myself. you should just have to add this to your list of sites you follow:

    http://feeds2.feedburner.com/CodeOfDoom

    hope that helps!

  15. July 11th, 2009 at 05:43 | #15

    Dear All

    I want to know the if i implement the actor director interface examle through abstract class than how many functions abstract class will conatin.what’s “2^n” meaning?

    Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.

    Please explain it’s urgent.

  16. Amit V
    July 26th, 2009 at 06:50 | #16

    Will be helpful if abstract & interface is differentiated with an example.

  17. Pratik
    September 20th, 2009 at 14:06 | #17

    I have read most of the articles about abstract class and interface and most of the interview they are asking practicle scenario.. they also don’t know about practical scenario. At the end of the interview they will ask as “Would you like to ask somemthing?” (with too much confidance on his/her face as they are having much knowledge) but when I ask to explain the question what they asked me about practical scenario of abstract class and interface. They also not able to give any practical scenario and explain some theary like this article. Dear Author, If you ask the question in interview you shoud definetely able to give real practical scenario. But these features are not really use full in developing applications like Employee system (one interviewer asked me to list down abstract class and interface for employee system) or actor director etc. But these features are only useful for developing system application like Microsof Word, Excel, Paint etc where you don’t have any easy method than these. If you give examplse of the actor, director or employee system something say, flight reservation where without using abstract or interface also there are other ways which can be used easily. But generally most of the companies taking interview they will ask this type of questions and once you join the company they are working on vb and asp (where no object oriented concepts are used) and the application started by some developer or team leader would have left the company and who ever handles the application will use their own logic and application becomes a mixture. These kind of application they will ask us to work on after asking these type of questions in interview (even though interviewer also can’t give the proper answer). Dear Author, please don’t mind and give real time scenario where without using abstract class and interface we don’t have any other easy way to use.

  18. September 29th, 2009 at 11:12 | #18

    Hi

    I am agree with Partik.I have face such kind of situation,where interviewer ask these question and when you explain they don’t agree on that because they have feeling like they are taking interview.

  19. George
    December 4th, 2009 at 07:16 | #19

    This is very helpful thoughts ….thanks

  20. Dave
    December 18th, 2009 at 14:08 | #20

    OMG, Wish I had read this YESTERDAY! I had an interview on the phone today and didn’t even have the oportunity to stare back like a deer!

    I have been a professional for 30 Years, I have even taught Advanced Object Orentation and I dre the paverbial BLANK!
    I tend to agree with Pratik but one can not be a Smart Axx in an interview!

  21. Tim
    December 31st, 2009 at 02:11 | #21

    @admin
    Well, many popular languages *do* toss one out: Python, C++, Dylan, etc. I don’t think I’ve ever missed having the distinction in any of these languages.

    I’d throw the question back: Gosling claimed to have omitted MI for simplicity, but is that for the language user, or for the compiler writer? Issues like this suggest that it’s merely the latter. OCaml programmers don’t spend any time sitting around discussing this, and they don’t seem to be hurting for productivity or type-safety or performance or anything else except possibly marketing budget.

  22. Pareen Vatani
    January 5th, 2010 at 14:18 | #22

    lets solve this in a easier way .

    Go for interface when u need programmers working on just the defination part where method name’s and arguments will stay the same .Thus that will maintain the naming conventions.

    Put methods in abstract class if defination is pretty much known.

  1. No trackbacks yet.