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 :) .

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

  1. ultra
    August 16th, 2012 at 00:38 | #1

    “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.”

    Why? This is a trend I’ve been subjected to in various interviews I’ve had in recent years. When I was the interviewer, I never bothered asking what people do in their spare time, outside of work, because it’s really none of my business. But I’ve had three interviews in the past year where the interviewer has asked me this.

    It just leads me to believe that 1) the potential supervisor (or the company) has no desire to train or develop employees for their personal or professional growth (read as well-being), 2) the company is trying to steal ideas (which there have been written cases of) with an “all-works-belong-to-us” clause or find out if someone is moonlighting, and 3) perhaps they are trying to gauge burnout potential.

    I made my subordinates learn by teaching and training them, not by leveraging their personal programming pursuits for thankless work tasks.

    I used to be a loyal employee of wherever I worked, but with this disturbing trend, it’s no wonder why the industry has gotten so cutthroat.

  2. Sourav
    August 16th, 2012 at 11:48 | #2

    Good description!!

  3. Jason
    August 17th, 2012 at 16:49 | #3

    I like to think of interfaces as a collection of behaviours you want the implementing class to have.
    And abstract classes would be a generic case of any subsequent subclass.

    I personally would only use an abstract class if I need to have a base class with some predefined functions, but if I wanted to ensure the existence and return types (…etc.) of functions, I would use an interface even if it meant an abstract class implementing an interface, and then defining those interface methods, that do not have a default implementation in the abstract class, as abstract methods for it’s subclasses to implement.

    It seems like extra work, but I believe that it allows for more decoupled coding…

  4. Mahesh
    August 21st, 2012 at 02:20 | #4

    hi all,

    I have a basic question, i understand why we need to use a class instead of interface for deriving thing, but my question is why should we use abstract class instead of normal class. we can add any members to the class any time?

  5. vijay
    August 23rd, 2012 at 01:21 | #5

    I am trying to find the difference in the google since long time.
    Now i found the exact difference from your article .
    Thanks for explaining the difference and when to use.

  6. Chip
    August 23rd, 2012 at 07:25 | #6

    I screwed the pooch on an interview yesterday where they asked this exact question. I had to admit that my OOP knowlege was not strong enough to give a qualified answer. :(

  7. August 25th, 2012 at 07:32 | #7

    Could you please explain us what changes we have to do in base class, if we go with abstract class.

  8. Mahesh
    August 28th, 2012 at 03:42 | #8

    answer is as simple as this..as we cant create an object for an abstract class, it is soley used as the base class where we can only inherit it..its a kind of best practice..we can also use a normal class as baseclass which makes no difference

  9. Pramod
    August 30th, 2012 at 11:05 | #9

    I think we are able to handled multiple inheritance using interface while common characterstics and behaviour of subclasses are handled thorugh subclasses.

  10. shilpi
    August 31st, 2012 at 09:10 | #10

    its really very good explanation…

  11. shak imran
    September 19th, 2012 at 15:13 | #11

    As discussion of abstract class you said,

    “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.”

    My question is i can do with it normal class. Why i need abstract.

  12. Anonymous
    October 2nd, 2012 at 23:26 | #12

    @shak imran
    Because the abstract class can also have abstract methods which children of the abstract class will be forced to implement, a good example of this is the Template Pattern

  13. Johan Nilsson
    October 3rd, 2012 at 17:18 | #13

    What a weird example with ActorDirector. If the instance of an Actor, Brad Pitt, suddenly starts directing films, how do you “convert” him to an ActorDirector object?

  14. srikanth
    October 8th, 2012 at 12:58 | #14

    Good explanation…

  15. Anonymous
    October 9th, 2012 at 20:25 | #15

    bad explanation. Got me more confused.

  16. Nev
    October 15th, 2012 at 06:52 | #16

    Really good explanation. Well done.

  17. Mr Private
    November 13th, 2012 at 14:20 | #17

    When you want to provide polymorphic behaviour in an inheritence heirarchy use abstract classes. When you want polymorphic behaviour for classes which are completely unrelated use an interface.

    And I TOTALLY agree with the guy that questioned why an interviewer would want to know what a person does outside work hours. Let me give the response that every person you have ever asked that question of wanted to give, but was afraid because he wanted a damn job —- Mind you own F’ing business.

  18. Anonymous
    November 27th, 2012 at 14:35 | #18

    you would want to change “extends” to “implements” in your example as both Actor and Director are interfaces.

  19. harshitha
    December 3rd, 2012 at 01:35 | #19

    its really very good explanation…

  20. Ala’eddeen Awwad
    February 3rd, 2013 at 18:56 | #20

    thanks alot :)
    very good exploration

  21. Sneha
    February 5th, 2013 at 02:36 | #21

    It’s quite confusing. A big para like a story. If you are an interviewer, I suppose you know what kind of answers you expect from a candidate and your this explanation just left me more confused on this topic.

  22. February 6th, 2013 at 03:07 | #22

    I found this posting , “When to use an Abstract Class and an Interface | Code of Doom”,
    relatively entertaining and also the post was indeed a wonderful read.
    Thanks for the post,Brent

  23. Anonymous
    February 6th, 2013 at 12:00 | #23

    @ultra
    The company want active people, not the one who comes and do work and go.
    That is why this question is asked, they want to know how geek the person is and whether his passion is his work or not

  24. Mayur Sirwani
    February 6th, 2013 at 12:00 | #24

    @ultra
    The company want active people, not the one who comes and do work and go.
    That is why this question is asked, they want to know how geek the person is and whether his passion is his work or not

  25. Anonymous
    February 14th, 2013 at 04:51 | #25
  26. mayur
    February 14th, 2013 at 04:52 | #26

    srikanth :
    Good explanation…

    @ultra

  27. March 1st, 2013 at 23:41 | #27

    I actually think this specific posting , “When to use an Abstract Class and an Interface | Code of Doom” electzgharta09 , quite enjoyable and also the post
    was a wonderful read. Regards-Jennie

  28. Anonymous
    March 3rd, 2013 at 05:48 | #28

    hummmm@harshitha

  29. Anonymous
    March 14th, 2013 at 06:00 | #29

    finally got to know what is an abstract class !

    Thanks :)

Comment pages
  1. No trackbacks yet.