Friday, February 6, 2009

Use of Abstract Class and Interface

When should I use an interface instead of an abstract class?

Use abstract Java classes when you want to provide some standard base code but want/need to force the user's
of your class to complete the implementation

(i.e., you create a skeleton implementation and the sub-classes must flesh it out)

Interfaces are useful when you do not want classes to inherit from unrelated classes just to get the required functionality.
For example, let bird be a class with a method fly(). It will be ridiculous for an aeroplane to inherit from bird class just
because it has the fly() method.
Rather the fly() method should be defined as an interface and both bird and aeroplane should implement that interface.