Monday, May 12, 2008

Interview: Interfaces Vs. Abstract Classes

What is the power of "Interface" in Java and support your answer with a practical example which could be understood by most Java programmers?

Answer: Interface helps in designing systems or software with high-level of abstraction. It helps design API and establish protocols between various systems being iteracted or interfaced. Let's take an example of java.sql.Connection. It totally depend on the implemented JDBC driver to define what the connection is doing. It could be a Oracle, MySQL database connection or it could be just a flat file based database connection. Same is the case with javax.servlet.Servlet interface. I can throw more & more examples. Anyway, the bottom line is... JDBC, Servlets, JMS, EJB etc. are all possible because of Interface.

I am not saying that is the best answer anyone can give or that is the only usage of Interface. Honestly, I should admit, I didn't know the real usage/power of Interface for a long time working in Java, until I reached a point where I felt... Yep... This is it. This is why interface was invented for...:)

I am not denying or underestimating the usage of abstract classes. And, I do think you can design APIs with just abstract classes. But, you almost had to fake some implementation to get high-level of abstraction. Abstraction is one of the biggest blessing in Software Programming. Think about OS level system calls, its all abstracted to the application level programs. We don't care how the file is being read or written at the byte level. As an application level programmer we do our job (of reading & writing file right by the application program we are working with) & expect the OS to do its job. I dont want to go off topic with all these metaphors. I think, I made my point clear.

Interfaces are great at specifying standards. Abstract classes help define frameworks. You cannot build an SDK out of interfaces. It doesn't give you anything but structure. In order to actually implement and distribute an implementation of one of these standards, you have to use abstract classes. You have to write functionality that can be seamlessly integrated with your client's derived classes.

(http://blogs.boxysystems.com/2008/5/9/power-of-interface-in-java)

No comments: