Java – Why use interface in Dao design pattern or other design patterns

design-patternshibernatejavaspring

Please see below components of a Dao design pattern:

Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.

Data Access Object Interface – This interface defines the standard operations to be performed on a model object(s).

Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.

Model Object or Value Object – This object is simple POJO containing get/set methods to store data retrieved using DAO class.

Why do we need an INTERFACE when we have a concrete class and why can't we use it directly? This might be a naive question but please help me get this thing clear. Not only in DAO design pattern but in other design patterns also use of INTERFACE is bit confusing. I agree this is related to code reusabilty and reduced coupling. But can anyone please explain a bit further.

Best Answer

Not only in DAO design pattern but in other design patterns also use of INTERFACE is bit confusing.

Interfaces is one of the best used concepts in Java. Let me explain this with an example: Say you designed a GPS device for car which looks into the map and automatically turns the car to the direction as seen in the map. This GPS device can be used in many cars like benz, fiat, etc. For each car, the mechanism of turning the left or right may differ depending on the implementation of the car system. So,these functions should be written by the car manufacturer and hence these methods are put in a interface, which is implemented by the car manufacture as per his car's implementation. The interface includes only a set of function declarations which are to be defined by the car manufacturer(In this case). Got it?

To learn more about interfaces and why they are useful, read this article.

My question is: Why do we need an INTERFACE when we have a concrete class and why can't we use it directly.

Among many other benefits that were pointed out in answers below, you can create many DAO classes for different data structers (derby db, huge stacks etc.), that implements DAO interface. The benefit is, that every class can be stored in DAO interface variable, its called polymorphism.