Friday, June 1, 2012

Interface or Abstract Class

What is the difference between an Abstract Class and an Interface?
Well, isn't it an interesting question or for few, a foolish question?

For a number of Java newbies, the only difference between two is, "You can't have method body in Interface.". Well, I would say that it is technically (Implementation vise) correct, but doesn't reflect the concept.

Abstract Class
An abstract class, is the most generalized form of an Entity hierarchy (In Java, a Class is an entity), such that it doesn't represent a real entity on its own, but provides a basis on which real entities can be build within that hierarchy. An abstract class provides a default behavior and also provide abstract behavior (Operations that must be override by the real classes).

Interface
An interface, on the other hand is a contract that states that you have to agree to provide following operations if you agree to abide by me, i.e. an entity that agrees to abide by the contract of interface, will have to provide the behavior (operations) declared in interface.

Interface or Abstract Class
Next question is when to use abstract class and when use an Interface? Though it many a depends on requirements as well, but I follow a thumb rule,
  • If I have to build a class hierarchy, I should consider generalization. Many a time I will reach to most crude form of generalization, i.e. at an abstract level. I would declare abstract methods and will also define common behavior for few of the methods. This would be my abstract class.
  • On the other hand, if I want to expose a particular behavior to the client, then I would define an interface. 

Further, I would suggest that one should go through different Java APIs, and spend some time understanding when and why they used interface or abstract class. Java APIs are excellent source for learning on building design blocks for any OOPs language.

1 comment:

Himanshu said...

A good introduction. This link would help understand this better as well - http://mindprod.com/jgloss/interfacevsabstract.html