0

I am new on using DAO in j2EE. I am a little bit confused about implementing this as I looked that there is already a concrete class but we are using an interface. Will anyone tell me in detail why interfaces are used instead of concrete classes directly?

tomtomssi
  • 1,017
  • 5
  • 20
  • 33
Abhishek Das
  • 23
  • 1
  • 6
  • In general, if there's a concrete implementation of an interface as well as the interface option, then there's choices in your design (there are other similar options in Java). With Java we know we can only extend a single class, therefore the interface may be the only option based on other design choices. – ChiefTwoPencils Mar 19 '16 at 06:38

1 Answers1

0

The Data Access Object is just part of a pattern, an abstraction above the data storage at hand. Since the details of the data storage might change by time (changing from MsSQL to MySQL or Oracle or any NoSQL storages) it is good practice to provide an API to the data, hence the interface usage in Java.

"Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation."

Since the clients will only see the public API of data through the interface, the implementation behind can be changed without any consequence (assuming that those changes adhere to the contract established by the API).

"Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data."

If the client would use a concrete DAO class instead of DAO interfaces then every time when the DAO class is changed and recompiled, the client should be also recompiled. In many cases this is undesirable since you don't want to stop your application and / or you have no control above the client.

On the other hand if the DAO interface remains the same, the classes which implement that interface can be changed / replaced with much bigger degree of freedom.

Note that the DAO interface is just one participant in a design pattern. You have to understand better how DAOs might fit / might not fit in YOUR architecture. You might want to organize data access differently based on your requirements.

One alternative might be using active records or data mappers, etc. But really, there are many different possibilities.

Source: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

Source: http://martinfowler.com/eaaCatalog/

Alma Alma
  • 1,641
  • 2
  • 16
  • 19