abstract vs interface

  • interfaces can have no state or implementation,data members must be public final static
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

 

 

Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.

Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).

 

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

 

 

 

 

posted on 2013-06-13 08:10  brave_bo  阅读(227)  评论(0编辑  收藏  举报

导航