Thursday, June 18, 2009

Interfaces, Inheritence and Hibernate

How to choose: Inheritence or Interface?
  • Idea 1: If the relationship is more an "is a", use inheritance. If it is more a "can be", use interface. Examples: TextBox "is-a" Control, ArrayList "can-be" enumerated.
  • Idea 2: If your object is a specialization of another object, use inheritance. But if the feature that distinguishes the derived class from the base class is something that other classes may need to support as well, an interface is a better choice.

1 comment:

Razib Shahriar said...

using interfaces is very important as it forms the basis of the delegation/decorator pattern - which is sometimes a great alternative to inheritance.
Consider the following scenario: A lecturer, student, tutor all are person. But the same person can perform more than one role at the same time.. using iheritance creates a messy hierarchy which grows rapidly as there are more roles.. Delegation/Decoration solves it nicely (ref: GOF design patterns book)