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. dedeepya
    February 7th, 2012 at 04:44 | #1

    liked it alot… :D

  2. gulam
    February 8th, 2012 at 11:41 | #2

    hhahahahah…. That is really gr8 before that i was totally confuse.
    Thanks Alot

  3. abcd
    February 9th, 2012 at 17:24 | #3

    i didnot get when to use abstract class can you please explain again..

  4. Ran
    February 11th, 2012 at 07:17 | #4

    Thank you . the best example for interface and obstract usefull for interview questions

  5. gargi
    February 16th, 2012 at 02:28 | #5

    Nice and easy to understand. . .Thanks. . :)

  6. GaRgi
    February 16th, 2012 at 02:29 | #6
  7. smh
    February 22nd, 2012 at 05:07 | #7

    can you telt me the real time examples for both..

  8. kathan
    February 22nd, 2012 at 05:16 | #8

    I am not sure but the example you have provided in “When to prefer an interface” is wrong.
    How can you extend two interface? You can only extend one interface, right?
    If I am wrong please let me know.
    Thank you.

  9. k24
    February 22nd, 2012 at 05:16 | #9

    kathan :
    I am not sure but the example you have provided in “When to prefer an interface” is wrong.
    How can you extend two interface? You can only extend one interface, right?
    If I am wrong please let me know.
    Thank you.

  10. J kumar
    February 25th, 2012 at 14:57 | #10

    Good explanation and abstract and interface
    Thanks

  11. sharavanakkumar
    March 1st, 2012 at 07:27 | #11

    These days software programmers lack the practical knowledge of oops concept. because they either told use the libraries created by programmers of long time. or modifying the existing codes.. the knowledge should be transfered by the programmers who created the primary project to all junior programmers otherwise the upcoming will lack knowledge leading to software product without quality.

  12. techpassionateguy
    March 2nd, 2012 at 12:23 | #12

    Other major difference in why to use Interface over Abstract class : Java supports only extending from 1 base class. So if your class needs to extend from multiple base classes, then Interface is the way to go.

  13. kishore
    March 9th, 2012 at 02:06 | #13

    Super.thanks.It is really useful..

  14. Devi
    March 9th, 2012 at 05:49 | #14

    Thanks.. Very useful…

  15. pradeep
    March 10th, 2012 at 14:12 | #15

    Thanks for the good article.
    Acted as a good refresher.

  16. Ricardo
    March 10th, 2012 at 20:29 | #16

    Nice article.
    Can you tell other typical questions like this?
    Thanks.

  17. Avinash
    March 13th, 2012 at 02:37 | #17

    Awesome, helped me understand the difference very well. thanks a lot.

  18. Junod
    March 14th, 2012 at 10:29 | #18

    Your answer was just as useless as the interview candidates your calling out in this post. You’re explanation is the canned answer you read on every dev. site in existence, this “is a” vs. “has a” relationship…please!

  19. Bozo999
    March 16th, 2012 at 04:37 | #19

    Well, I thought your article was well-written and very helpful. Perhaps Junod should be canned.

  20. fellow programmer
    March 17th, 2012 at 20:34 | #20

    @kathan
    you are Wrong
    You can certainly implement more than one interface in Java
    http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
    Read the last paragraph in this page

  21. KruZ
    March 19th, 2012 at 02:02 | #21

    nice article… thanks

  22. Rahul
    March 19th, 2012 at 05:11 | #22

    what is the technique of replacing a character in a string without using the replace()method? can anybody help me?

  23. March 19th, 2012 at 14:43 | #23

    nice one splendid explanation

  24. March 19th, 2012 at 14:48 | #24

    @Rahul

    let me help you soon just give me your email address mine its scissor_kaichi@yahoo.com

  25. sandeep
    March 23rd, 2012 at 06:35 | #25

    worst examples i have come accross ever…

  26. Anonymous
    March 24th, 2012 at 14:09 | #26

    @k24
    That’s one of the main differences between an interface and an abstract class. You can only “extend” (inherit) one abstract class but you can “implement” as many interfaces as you like.

  27. Ali
    March 27th, 2012 at 01:21 | #27

    Really You Have tried to explain it in a better way but it’s no very clear to Understand in a easy way.

  28. AnilL
    March 27th, 2012 at 05:55 | #28

    Nice understanding. I had to read at 2 times to get this point but now it is very much clear. Thanks for your efforts and your explaination.

  29. biswababa
    April 1st, 2012 at 08:45 | #29

    Sorry to say, you are also repeating the same http://www.basicinterviewquestions.com concept. Nothing real or new highlighted in this article.

    Do think positive

  30. Arden
    April 2nd, 2012 at 12:03 | #30

    I need to chime in here. For the last ten years or so, I have worked as a programmer (VB and C#.net). I can honestly tell you that I have never had to create an abstract class OR an interface. Why is that? Because my work experience in this field has consisted primarily of two activities: 1. Debugging code that has been written by others and then rushed into production without enough testing, and 2. Reusing/copying/pasting existing code on those rare occasions when I am tasked to create something “new”. My question, directed mainly at hiring managers and others who are in the position of conducting interviews, is this: I’m sure that OO concepts have a great deal of importance at some level, but if my time as a programmer has mostly been spent in the trenches, putting out fires, and performing “meatball” code surgery like a M*A*S*H surgeon, why would you expect me to truly understand things that I have not seen or worked with since reading about them in a textbook a decade or more ago? Let me tell you of my capabilites: I understand basics, how to troubleshoot and step through code, code syntax, writing decent code and maybe a simple class or two, working with source control, dealing with other human beings, and just trying my best to be reliable and show up to work every day. And, for what I don’t know, I have Google. Go ahead and laugh, but there are tens of thousands of other “software engineers” just like me. Ask me anything you want. If I give you a satisfactory answer as to what an abstract class is, the only thing that will tell you about me is that I can memorize things pretty well after a night of cramming – but don’t expect me to be able to write an abstract class on my first day of employment. And, trust me, this lack of knowledge has not impeded me in any way for my last ten years working with code.

  31. rk sharma
    April 2nd, 2012 at 13:52 | #31

    pretty good explanation..thanks a lot..please do posting

  32. kkratos100
    April 3rd, 2012 at 13:27 | #32

    Arden thanx for explanation……..you r my inspiration…

  33. Abhilash
    April 8th, 2012 at 03:01 | #33

    By far the best i have come across

  34. Kamal
    April 9th, 2012 at 06:20 | #34

    I think that was helpful. but the question is why to use abstract while you can use concreate class ??

  35. Swati
    April 11th, 2012 at 16:54 | #35

    Nice Explanation !! thanks a lot..

  36. Anonymous
    April 11th, 2012 at 22:16 | #36

    Haven’t found a better explanation!

  37. venkat
    April 12th, 2012 at 12:00 | #37

    thanks a lot i get the right answer on this.

    txssssssss

  38. satish
    April 14th, 2012 at 12:24 | #38

    i was very much thankful to u

  39. p
    April 15th, 2012 at 01:00 | #39

    @Marcel, thanks for the superb and simple article. It was really useful for both learning and preparing for interviews!

    @Arden, I do agree with you to a large extend. Depending on the work we have been dealt we can be doing almost no coding from scratch and there are thousands who do similar work day in and day out. Infact, though i hate to admit it, i too have faced a very similar situation for most projects i have worked on.
    But my opinion is that we can still learn some of these basics as this will help us understand why the original developers wrote the code in the way they did so.
    You also cannot rule out the possibility that we might have to write a whole new application one of these days and at that time, this learning will benefit us (and the debuggers who end up debugging/adding to our code in the future!)
    As a side note, some of the most satisfying moments are when we(the debugging guys) actually recognize areas where the developers did not make the right design decision (or at least we feel so!) … but this is quickly followed by the sadness brought by the realization that we debuggers cannot change code that is otherwise not labelled by the users as ‘BROKEN’ :(
    As for the interviewers, the fault is not with them but with the companies that employ them. Companies need to accept the fact that not every developer actually develops day in and day out. Once they accept that, the interviewers would begin asking more questions dependent on the type of work we used to do in the past.

  40. vilas
    April 18th, 2012 at 11:58 | #40

    superb example and understanding. Thank you friend

  41. Rahul
    April 19th, 2012 at 10:38 | #41

    Awsum explanation.Thanks for such a crystal clear description about interfaces and abstract classes

  42. Naresh
    April 25th, 2012 at 08:09 | #42

    Awesome delivery…superb…….I never found such description like this regarding on Abstract & interfaces..

  43. Shal
    April 26th, 2012 at 03:35 | #43

    Really very helpful…………

  44. Brian
    April 28th, 2012 at 14:00 | #44

    @kathan

    One interface can extend any number of interfaces.
    try following compiles
    interface x{} interface y{} interface xy extends x,y{}

    One class can implement any number of interfaces.

    One class can extend only one class.

  45. Mac
    May 3rd, 2012 at 08:47 | #45

    @Arden
    I completely agree!! Its ridicoulous the questions they are asking on phone screens and interviews. Us heads down programmers don’t know the concepts we are using we can only do what we need to to get the job done correctly and on time.

  46. kevin
    May 7th, 2012 at 16:37 | #46

    @Arden

    Technical interviews are used for the interviewers to whip their junk out and lay it on the table. They are usually more interested in letting you know how much they know instead of evaluating how well you could do the job. It’s probably they only time in life were they will get to intimidate someone.

    I guess it’s payback for every dodge ball they had thrown at their head in gym class.

  47. suresh yadav
    May 9th, 2012 at 10:16 | #47

    Assam explanation..

  48. AndrewGoel
    May 10th, 2012 at 06:05 | #48

    Good explanation.

  49. Mukul
    August 10th, 2012 at 05:58 | #49

    @Arden
    you are absolutely right Arden. Interview has nothing to do with original work. You may not know the definition,but can implement it better than any body else. All questions asked in the interview are useless. Something important in real coding is how reusable and efficient your code would be and how much it costs to your systems,no matter how you implemented it. That must be unbreakable and reliable.

  50. Dinesh
    August 12th, 2012 at 00:22 | #50

    Nice explanation.

Comment pages
  1. No trackbacks yet.