Learn This: When to use an Abstract Class and an Interface
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.
.
Feel I left something out? Disagree? Leave a comment
.
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.
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”.
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!
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.
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?
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
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.
hi there is some problem with ur rss feed plz resolve it ,it is a gr8 blog want to read it on feeds
Shouldn’t there be an “implements” instead of “extends” in this piece of code?
public interface ActorDirector extends Actor, Director{
…
}
@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!
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
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
Hello, I can’t understand how to add your blog in my rss reader.plz tell me thank you.
@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!
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.
Will be helpful if abstract & interface is differentiated with an example.
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.
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.
This is very helpful thoughts ….thanks
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!
@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.
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.
Basically Use Interface when
1) You want to make a contract/force all the concrete subclasses to implement methods of interface.
2) Use abstract class when you want to provide/force some functionality your self, and remaining subclasses can provide. One of the good example is template pattern where the base class/abstract class has a final method(which provides the template) and other methods are abstract, so all subclasses can override the abstract methods but they are forced to use the final method of the superclass.
If an interface has 1000 methods then implementing class should implement all those 1000 methods …How do we avoid this situation of
implementing those 1000 methods …This is a question I ask in every interview
I am a professional developer for over 20 years with strong object oriented skills and designs. I agree with Shaun. I would definitely stare back at the interviewer like DUH–if you don’t understand how complex this is, then I am just going to give you the canned answer becasue that’s probably what you want (because by asking this question you don’t really understand the nuances of interface design).
Here is the basic problem with asking the question as written on this site. IT IS LANGUAGE SPECIFIC. The “concept” of abstract versus interface is different depending on the language you are using. A good CS Programming Languages course will make you appreciate that. This question is very theoretical. For example in C++ the distinction is very minimal and very context oriented–in C++ an “interface” is an abstract class which provides no implementation, has no members, and no constructor. But to Anil’s point, what if I had a class with 1000 members on it. I could code an abstract class with default implementations and use that–in C++ this can still be used effectively as an interface. There are some other subtle complexities with interfaces and template design in C++, but I won’t go into that here.
However, move to C#. The same is not true. Why? Because in C# the langauge only supports single inheritance, thus if you use an abstract base then you cannot offer any more interfaces–or rather you are stuck with a fat interface. Since fat interfaces (i.e. putting all service methods into one class) is generally not a good practice we would like to separate out our interfaces based on the services they provide–the only way to do this in C# is through an interface. (A class can only extend a single base class whereas it can implement multiple interfaces; contrast to C++ a class can implement many base classes).
Thus the answer to your question is “it depends.” What are our use cases? What is our language we are coding in? What runtime dependencies do the syntactical constructs impose? What is the design goal behind class abstraction? based on these considerations, then I could answer why I would use one versus the other. In my experience most developers can’t properly code an interface without suffering from some unexpected coupling issues.
Choosing to use an interface as a design construct should be a well thought out and thorough examination of how the code/class will behave.
well, i guess you wouldn’t hire me. ive been developing elegant yet sophisticated intra/internet apps that incorporate plenty of OO-design for 10 years and never found it practical to use interfaces in more than a few instances.
i was asked this question once, and resented it. its for a college kid just out of CS101, not proven professionals. unless you are a coder of advanced gaming and/or AI systems you BETTER NOT be spending so much time contemplating interface VS abstract. if i was your boss i would NOT be happy.
i am willing to bet most if you are web developers for backoffice business process automation systems and NOTHING more advanced than that. to feel the need to use such advanced OO concepts is overkill and over-coding. just make sure you follow good agile patterns, proper namespacing and standards, and enforce it accross the team, and you will have successful projects.
very nicly…described…will u please demostrate OBJECT VS INSTANCE .AND object vs object variable . instance vs instance variable
Very nice tips, i agree with you thought i didn’t think about it too much before, but i think this way we can make think easier.
@Pratik
Good Pratik
@imustbedumbthen I concur! Interviewers get their questions from websites instead of practical everyday instances!
I completely agree with ilovebedlum. I’ve worked as a web developer for more than 12 years and have worked with ASP.NET for about seven of those years. I’ve NEVER ONCE had to worry about interfaces or abstract classes, nor have I ever seen any other web developer I’ve worked with write such code.
Yet just this afternoon, I was asked this question during an interview. I didn’t have a response except complete surprise. The only types of classes I’ve ever had to deal with are standard classes and partial classes –that was my answer.
I don’t think it’s a good question to ask today’s web developer. It belies someone’s experience and expertise in dealing with the real world.
I am a web and windows developer in .NET.
And not to be mean Tina, but perhaps you’ve never been asked to build a framework for use in a distributed system?
Perhaps you’ve never abstracted a Member system (not a Membership provider), or a shared Business Layer for a distributed system. In such cases, abstract classes vs interfaces is a serious concern when multiple inheritance is not an option. Therefore, I think it’s an applicable question to any developer, whether you’re on the web, wmbedded, mobile, or windows/OS developer.
However, as was mentioned above, it does vary depending on the language. In C++, it’s contextual and (in many cases) just depends on what the developer(s) is/are comfortable with, whereas in .NET it’s more specific.
ya i totally agree wit u. tis is wat i expected.
here u mentioned like”Abstract class will have collection of related method’s declarations (actually class is a collection of related objects in oops)but interfaces ll have unrelated method’s declaration …
IN my perspective “a class which cannot defined properly tat class can be declared as abstract for example country is a class which cannot be defined exactly which country it is, then we can declare it as abstract class …
a country may have their own currency,capital and so on but almost all nations will have tis common methods n properties but the problem is “WHICH COUNTRY?”
in this cause we can go for abstract class n interfaces
Interface is just like abstract but its not a class but its an entity in other words its a collection of unrelated methods ..
Here all are talking about its implementation and its syntax but u only spoke about its exactly about its core concept..
reply me if their is anything wrong or any modifications
For previous commenters on this article who say that they have no need to understand interfaces, let me say this as gently as I can – Imagine a world without hardware interfaces – no USB, no IDE, no SATA, no FireWire, no PCI, no AGP, heck no “AA”, “AAA” batteries and OMG no A/C mains three-prong outlets and you’ll soon get the picture of how important interfaces are. Trouble is, we get so used to these hardware interfaces everyday that we fail to see how useful they can be in a plug-and-play software environment. If you develop in an industry where interoperability is a prime requirement, you’ll pretty soon realize that conforming to an interface is a very basic skill that you need. If you want to develop components that can be swapped in and out for new functionality or improved performance, a knowledge of interfaces and programming to interfaces is important. Please do not discount good practices just because you have not had the opportunity to use them in your careers spanning however many years – use them before dissing them, and then provide us with examples of why using a solid software engineering principle/practice did not provide you with the promised benefits.
Similarly abstract classes encapsulate common behavior and provide default implementations to subclasses (as has been mentioned elsewhere) and save both initial effort/cost and maintenance effort/cost, along with other engineering benefits.
i Don’t Find it useful at all..!!
Hey If u r in a position to make fun of some sites then u should hav the real potential to explain it in a very simple way so that even a new comer can understand it..!!
“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”
i dont find it simple at all..!!
u have made it still complicated..!!
u just browse google for definitions think u may get even a very very simplest n easiest explanation..!!
@Chax0
I wholeheartedly agree with you. It took me a while to grasp the concepts of interfaces and their usefulness, but as soon as the composition-over-inheritance dime dropped it all made sense. It is abstract though, in the just-get-it-done environment that many of us are unfortunate to be trapped in it can be difficult to motivate why good practice leads to good results since bad practice often gets results (however wrong) quicker. It’s like agile methods; when followed properly your development effort is linear, whereas otherwise the old proverb that the last 20% of work takes 80% of the time holds somewhat true.
Furthermore, using interfaces as contracts is key to proper unit testing. Mocking without interfaces is painful at best. Unit testing is also a concept that you really need to experience to understand the value of. I mean, once you’ve realized how many regressions you catch by unit testing it’s ridiculous to go back.
I think I spotted a typo at the end:
you will known >> you will know
Nice article nonetheless.
Here is a nice article on this. http://mindprod.com/jgloss/interfacevsabstract.html
Nice article, this helped me a lot.
If I was asked this question I’d just say I use abstract classes when implementing the Decorator pattern and use interfaces for everything else. Then I’d sit back and wait for them to decide how much to increase what they were planning to offer me.
L0lz… srsly, in the last 5 years I’ve written abstract classes maybe twice. I think they’re a pretty low value construct in languages that are trying to be modern. I’m not flaming C++ (or Java), but interfaces are almost always going to win. I think for an abstract class to make sense, you’d have to be designing a type hierarchy where the base type had a fairly large surface area and some core functionality that usually did not vary but occasionally might. Even if that were the case, I’d take a closer look at something like that in a code / design review to see if there wasn’t a better way to implement it.
It strikes me as scary that the “right” answer to this interview question might be, “I can version my code easier with abstract base classes than with interfaces.” I think if you choose a design based on inheritance where you are *expecting* changes in the default implementations of base class methods then you have chosen a poor design. Other commenters have said it… favor composition over inheritance and encapsulate the expected variation.
Nice explanation.
Hi,
it is nicely explain.
in fact i have used the disussed features in our project
and forgotten
but your article had struck well .
Hi,
Question: What abt peformance? Which one is better and how? In design phase how can I decide?
Nice article.
Thanks,
Sid
any real time example
thanks sir for the info…
it took me a long time figuring when to use abstract instead of interface and vice versa so tnx
Really good article explaining the diff of interface abstract class to its best, i already banged some interviews without knowing the ‘real’ fact
@funkyboy
Interfaces can extend other interfaces.
Nice post and great discussion in comments. Thanks.
This question has been asked many a times in interviews.
Josh Bloch said himself in Effective Java 2d:
Prefer interfaces over abstract classes
Some main points:
Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.
Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.
Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.
Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.
On the other hand, interfaces are very hard to evolve. If you add a method to an interface it’ll break all of it’s implementations.
@Marcel
Do realize the comment above is spam? He is just getting links to his site sears parts now the question you should ask your self is am I doing the same thing =)