Thursday, October 06, 2005

Interfaces vs Abstact Classes

1. multiple inheritance :
A class may implement several interfaces whereas a class may extend only one abstract class.

2. default implementation :
An interface cannot provide any code at all, much less default code.
An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

3. constants:
Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.

Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.

4. Third party convenience :
An interface implementation may be added to any existing third party class.
A third party class must be rewritten to extend only from the abstract class.

5. plug-in :
You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the inteface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design.
You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad.

6. homogeneity :
If all the various implementaions share is the method signatures, then an interface works best.
If the various implementations are all of a kind and share a common status and behaviour, usually an abstract class works best. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homo-geneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.

7. speed :
Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty.
abstract classes are fast

1 Comments:

At 5:02 AM, Blogger sarmad said...

what is the use of token \f

 

Post a Comment

<< Home