Originally posted by rahul mehra:
why is interface needed in java.... if we say that any class which implememnts a particular interface has the flexibility to define its method in its own way..then we might as well as declare a class with the required method....
why do we need to define an interface.... ???
can anybody give me the basic idea.....
In addition to the use within the Java language itself that Stan talks about, interfaces are very useful in another way. A classic example of the power of interfaces is the
JDBC (Java Database Connectivity) API. If you look at the API docs for the
java.sql package, you will see there are a lot of interfaces defined for which there are no actual implementing classes. It is left to to the database vendor to actually implement the class. In fact, Java itself does not have implementations of these interfaces.
This allows me to write code based on the interface, say a Statement and a ResultSet, that works regardless of the underlying database.
That code is programmed entirely against the interfaces in JDBC. At runtime, I may use the MySQL JDBC JAR file in my classpath which has the ResultSet and Statement implementations for the MySQL database; Or I might use the Apache Derby JAR, or the Hypersonic SQL DB JAR, or Oracle JDBC JAR, etc. It doesn't matter; my code runs the same because I programmed to the interface. This makes the code far more flexible. I can switch the underlying database without having to make any code changes. This prevents me from getting locked into a specific database vendor. (At my old job, when our database vendor was going to significantly raise licensing costs, we simply switched database vendors with no code changes. We could do such because of the JDBC API.) The JDBC API also provides more general flexibility. For example, in my project at work, our
test code runs against a very light weight (and free) in memory test database; where as the same code, when in production, runs against a full scale database.
That is very powerful and useful.
p.s. you can read about the
Diamond of Death Venkat Sadasivam mentioned at Wikipedia.
[ August 16, 2008: Message edited by: Mark Vedder ]