Interface vs Class

I have read about the difference between Java Interfaces and Classes and understand it to a reasonable degree.

What is confusing me is the following. How come java.sql.Connection is an Interface? I ask this because I can create a Connection object then call any of the methods from the interface.

example:

cstmt = connection.prepareCall("{CALL Master.."+strStoredProcedure+"(?,?,?,?,?,?,?,?,?)}");

prepareCall is a method in the Connection interface. By definition an interface only declares methods but does not implement them. The above example leads me to believe that the java.sql.Connection interface has implemented the prepareCall method because the class that contains the example statement does not implement the Conenction interfact but just uses the methods in calls.

Thanks for any help in clarifying my understanding.

[867 byte] By [Dean@CSCa] at [2007-11-26 14:27:19]
# 1

the JDBC driver package you've been given by your database vendor provides an implementation of the Connection class for you to use. that's what you're invoking methods on. in order to use any old JDBC driver, your code needs to only deal with the Connection interface. that's the point of interfaces.

this is an illustration of why we "code to interfaces rather than implementations"

georgemca at 2007-7-8 2:20:53 > top of Java-index,Java Essentials,New To Java...
# 2

> What is confusing me is the following. How come

> java.sql.Connection is an Interface? I ask this

> because I can create a Connection object then call

> any of the methods from the interface.

An interface can have objects. Those will be the objects of the implementing class.

> By definition an interface only declares methods but

> does not implement them. The above example leads me

> to believe that the java.sql.Connection interface has

> implemented the prepareCall method because the class

> that contains the example statement does not

> implement the Conenction interfact but just uses the

> methods in calls.

No, the Connection interface does not have the implementation for the methods in itself. The implementation for java.sql.Connection interface is available within the driver jar for the particular database. This implementing class is the one which has all the code necessary for the method to work. The beauty of interfaces is that the object of your implementation class is treated as the object of the interface itself and methods can be invoked on it as if to appear that the interface itself is performing everything. The actual implementation is still within a class implementing the Connection interface but methods can be called on the interface as if they were called on a class itself.

aniseeda at 2007-7-8 2:20:53 > top of Java-index,Java Essentials,New To Java...
# 3
Thank you very miuch for the quick replies. I thought I was going crazy. Clears it up perfectly for me.
Dean@CSCa at 2007-7-8 2:20:53 > top of Java-index,Java Essentials,New To Java...