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. blake
    November 22nd, 2010 at 05:03 | #1

    Well some it’s the interviewers that get it wrong. I was asked BY an interviewer this question, and I was not happy with . They said it was mainly for multiple inheritance but I am still very skeptical…I’m not saying mult. inheritance isn’t an important feature, but I’m saying that’s not the main reason why you have multiple inheritance. I didn’t argue with my interviewers but I guess I should have.

  2. blake
    November 22nd, 2010 at 05:05 | #2

    @blake
    OK I didn’t proofread. What I meant to write was:

    Well sometimes it’s the interviewers that get it wrong. I was asked BY an interviewer this question. I answered but they were not happy with my answer. I was also not happy with their answer! They said it was mainly for multiple inheritance but I am still very skeptical…I’m not saying mult. inheritance isn’t an important feature, but I’m saying that’s not the main reason why you have interfaces. I didn’t argue with my interviewers but I guess I should have.

  3. Ramkumar Thangavel
    November 22nd, 2010 at 20:24 | #3

    Thanks….It seems, now I have good answer and can move towards to provide right decision.

  4. Phoe
    November 26th, 2010 at 14:41 | #4

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

    What if you add a new abstract method to the base (abstract) class – doesn’t that cause all your (concrete) subclasses to break as well?

    If you are not adding new methods, wouldn’t a concrete base class have the same advantages ( you override the methods instead of providing sub-class specific implementations)?

    I am trying to sort out other reasons why I want to use an abstract class (other than not wanting it to be instantiated – and why not?)

  5. rak
    November 30th, 2010 at 08:24 | #5

    I dont think that above explanation gives the correct answere, below is the link where its described in proper reason and way for “when to use what”

    http://en.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F

  6. December 11th, 2010 at 08:17 | #6

    It’s good that people are able to take the loans and that opens completely new possibilities.

  7. December 18th, 2010 at 15:41 | #7

    Good post, I found it very helpful as I’m guilty of learning the book definition and not actually being able to give good examples of each in the real world. Thanks!

  8. Kuldip
    January 3rd, 2011 at 10:29 | #8

    Best example i have ever seen thanks that’s clear my picture about interface and Abastract class.

  9. But
    January 12th, 2011 at 21:33 | #9

    rak :I dont think that above explanation gives the correct answere, below is the link where its described in proper reason and way for “when to use what”
    http://en.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F

    but

  10. Anonymous
    January 30th, 2011 at 14:44 | #10

    the best ever i find. its really good

  11. Pradeep
    February 6th, 2011 at 14:25 | #11

    @Phoe:

    I think concrete classes can do whatever an abstract class can do. But just for the sake of cleaner and clearer design, one of the pros of OOP, we use abstract classes or interfaces.

    For example: If you have a super class Figure which is used to calculate area of a figure like a rectangle, square, triangle or any other polygon. This figure SHOULD require dimensions to be passed to it to calculate area. But area formula differs based on the type of polygon. So it is better to calculate area in respective sub classes instead of defining it here as say area = NULL.

    Now if subclasses say Triangle and Rectangle wants to use the super class. We have two scenarios:

    1. Using concrete class: Here you can define some body or no body in the area() method. But if you don’t define area at all in the super class then all subclasses might define it the way they like like area1() or triangleArea() or areaRect(). Some folks might not even define the area because they don’t that the purpose of that super class is to calculate area and not forming a polygon object by passing dimensions as arguments in the constructor(let us say). This makes things a little messy.
    2. Using abstract class: Here you don’t define the area method. But you enforce the subclasses to define the area method in the way it is defined in the super class.

    This is just for cleaner and clearer design.

    3. Using interfaces: This will have same kind of abstractness in the design but for some reasons(probably for IS-A vs CAN-DO differences) noted above we can choose whether to use interface at all or not.

  12. Anonoymous
    March 8th, 2011 at 03:57 | #12

    Article is nice, but what to do when the interviewer is not known the actual differences.

    for example (real interview with PATNI Computers Ltd.): like an abstract class may extend Interface, Abstract class or Class but Interface only implements Interface. I put this difference in front of Interviewer and he reject me.

  13. Nathan
    March 17th, 2011 at 08:00 | #13

    I think it also is important to mention a couple of other things.
    Such as speed and Access.
    Most cases speed is not an issue however note that interfaces require more time to find the actual method in the corresponding classes. Although it may be minuet. Lastly abstract classes give you the ability to limit access, interfaces are always assumed public…

  14. Nishant
    March 18th, 2011 at 03:59 | #14

    Hi

    This is a very relevant article for Abstract class and Interface.We know what are they but we don’t know where to use them.

    Thanks

  15. Jeremy
    March 29th, 2011 at 14:39 | #15

    @blake

    That’s the problem with technical interviews. There is more than one way to skin a cat. I may use something one way and the interviewer may use it another. If my way doesn’t match the interviewer’s way, I don’t get the job.

    All technical interviews are for is so that the pretentious interviewer has an opportunity to show their “superiority” to the interviewee. People who are all-technical should never give an interview because they don’t know how to adapt and ask questions in ways the interviewee will understand. It’s usually their way or the highway.

  16. Brian
    April 18th, 2011 at 18:25 | #16

    Wow your like the first person i’ve seen mention Flex! I think if someone asked me a Flex question in the interview i’d refuse the job :P

  17. Malle
    April 22nd, 2011 at 10:31 | #17

    I agree with Phil on this “What if you add a new abstract method to the base (abstract) class – doesn’t that cause all your (concrete) subclasses to break as well? ” . How is it different from an interface?

  18. Karthik
    May 12th, 2011 at 01:02 | #18

    hi,
    Thanx for the article..i thibk this would really help anyone to know the exact scenario of using abs classes over interfaces…

  19. santhosh
    May 13th, 2011 at 14:00 | #19

    Great Perception of the Language and concept

  20. patripat
    June 6th, 2011 at 11:47 | #20

    I am still confused :(

  21. Sachin Gupta
    June 12th, 2011 at 06:02 | #21

    Hi,
    I clearly understood what is difference between these two dam useful concept of OOPs.
    But I would like to know how can we decide what should be useful that right place. I will give you one exmple..
    I have one project where I am going to design architectural structure of one building…
    there are 2 floor, each floor has 2 flats. Which is in rectangular in shape….. each flat will be having 4 rooms each one will be having two window. and one door…. back and front side.

    I appreciate if somebody can help me to design this in proper way.

  22. san
    June 15th, 2011 at 02:13 | #22

    Excellent answer Evere I seen .. thanks keep going

  23. Anonymous
    June 18th, 2011 at 10:58 | #23

    superb explanation

  24. sandeep
    June 20th, 2011 at 23:22 | #24

    This is also confusing. When to use ..what ? no practical scenario…explained.

  25. July 7th, 2011 at 02:05 | #25

    Thanks for your elaborated information which would help me to understand better OOPS concepts . As you explained above Interface is something can-do-this and Abstract class is for “IS-A ” relationship . Intefrcae is superset to abstract class I feel . because if you implement interface the child class has to give implementation to all methods , if you dont the child class becomes Abstract class . keep your views and ideas .

    Thanks
    Sitaram PV

  26. venkates
    July 13th, 2011 at 05:36 | #26

    Why should we use an interface at all. We can directly provide the method implementation in the class itself right?why implementing that andd……
    I have never used an interface in project that is reason why I am asking the question.

  27. Muni
    July 27th, 2011 at 05:24 | #27

    Its really good material with good examples. really good one.

  28. Akrma
    August 7th, 2011 at 01:54 | #28

    I just want to know, As I know abstract method is just name of class which doesn’t do any thing. My question, is why do we need to have such kind of method, while while writing for each class

  29. August 14th, 2011 at 03:29 | #29

    @blake
    Hi @blake, Every thing in oops is because of re usability of code. may be that interviewer wanted to hear this.

    Any way Marcel your article was good and well written and explain with good examples. Thanks. now i m ur fan :)

  30. arrow
    August 21st, 2011 at 11:59 | #30

    this stuff is been very useful thanks man!!

  31. Anonymous
    August 29th, 2011 at 21:23 | #31

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

    please can you show us the 2^n possibilities..

    Thank you very much in advance

  32. Anonymous
    September 15th, 2011 at 22:41 | #32

    I faced one of the fucking interviewer and he is the best fucker caz he is the real fake guy… he is my senior in college, and he removed his p.g and placed vast exp , join as a lead role

    fucker interviewers…….

  33. manoj
    September 22nd, 2011 at 10:29 | #33

    Excellent article..I like to see a full fledged example though..Helps people understand even better.

  34. Eile
    September 27th, 2011 at 21:24 | #34

    yeah, I don’t really like technical interview. I will fail even the entry level interview. I got luck, all the positions that i got, they made you write real code. And I’m good enough for Intel and fail those interviews. That means technical interview are waste of time. Go hire people who only remember the definition. I can’t even give you the definition of Encapsulation or polymorphism.

  35. Eile
    September 27th, 2011 at 21:28 | #35

    When i write WCF applications, it requires you to use interface because otherwise people can’t call your classes.

  36. jeff
    September 30th, 2011 at 23:30 | #36

    @imustbedumbthen +1000

    the author is an idiot

  37. Anonymous
    October 5th, 2011 at 10:30 | #37

    auther is an idiot…………………dear auther improve ur self……..

  38. makubex
    October 5th, 2011 at 19:16 | #38

    not the best description. also, author used extend when actor and director is an interface.

    public interface ActorDirector extends Actor, Director{

    }

  39. makubex
    October 5th, 2011 at 19:23 | #39

    i stand corrected, http://en.wikipedia.org/wiki/Interface_(Java) – syntax for interface extending another

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

    not the best description still….

  40. Anonymous
    October 28th, 2011 at 12:03 | #40

    for me it’s a good read..

  41. Lalit Vats
    November 2nd, 2011 at 12:46 | #41

    hi,
    i think this is the best way to describe both.
    thanks

  42. Ajay
    December 1st, 2011 at 16:24 | #42

    Hi,
    thanks for your brief description but i didn,t understand the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities of using abstract class.
    thanks

  43. sathiya
    December 6th, 2011 at 13:48 | #43

    it is bit confusing…go ahead with MSDN ariticle..really very nice
    http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx

  44. Ronald
    December 9th, 2011 at 22:27 | #44

    @Anonoymous
    ha ha,,, u r right Patni Guys are bit hard, they dont know the real concepts and proof, The same way it happened to me.When i told the Functional part of CMS with livewire publishing and content Editing, i have bypassed the interviewer’s comments which lead to an argument and ultimately i was rejected. The thing is the interviewer also should be smart not like Patni Guys….

  45. Ramesh
    December 16th, 2011 at 22:27 | #45

    You mentioned you don’t need to change base class if a abstract class is modified. I think the base class will be affected if a abstract class is modified.

  46. December 17th, 2011 at 07:33 | #46

    Interview is a discussion not an interogation

  47. johndeveloper
    December 22nd, 2011 at 08:22 | #47

    I qet this question ask to me all the time interviewers that all the time. The problem is when the explianation of an interface and abstract class should be good enough.

    When I explain to you that an abstract class can have some its methods implemented and some of them not implemented it means Abstract classes allow you to provide default functionality for the subclasses.

    When I explain to you that I can implement more than one interface means that are there are posiblilties that i do not want to implement both interface hence I would have put all the methods in one interface and not two.

    I reason why for the ‘deer in headlights’ look, is he just told you the differences. He assumes the you are intelligent and the usaged is implied.

    The good thing about this article is I now know how to formulate my answer for an abstract class and interface to answer you next question before you ask it. If you ask it anyway then I know you are asking the question just to ask the question to look intelligent.

  48. Batman
    January 6th, 2012 at 03:59 | #48

    I think both should be used at all times. The abstract class should implement the interface. This gives the client an option…flexibility.

  49. Thor
    January 8th, 2012 at 11:31 | #49

    Wish I had read this before my last interview. :) While this is a well known concept and I have done this in projects that I’ve designed / led, I did the classic deer in headlights and “ummm” response to it. This article is a good refresher and has clear examples. Thanks for posting it.

  50. Anonymous
    January 28th, 2012 at 10:08 | #50

    Awesome article !!!

Comment pages
  1. No trackbacks yet.