ajava
ajava

Reputation: 77

JDBC Connection interface object

In java.sql package we have Connection interface to establish connection with database.

And with the help of DirverManager class we can get the object of Connection interface. Ex.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:DNS");

But I have some confusion --- if Connection is an interface then how can we get the object of Connection interface?

Please clear this confusion.

Upvotes: 0

Views: 7404

Answers (3)

user2181047
user2181047

Reputation: 1

In J2EE, we code with Interfaces rather than classes as from vendor to vendor and driver to driver the class name change. To get the implementation class name use getClass().

Upvotes: 0

sudhir
sudhir

Reputation: 11

Oracle's T4CConnection class implements the Connection interface and Mysql's JDBC4Connection class also implements the Connection interface.

This means your con reference variable in the line below holds either a T4CConnection class obj if you load Oracle Driver or a JDBC4Connection class obj if you load mysql driver.

Connection con=DriverManager.getConnection("jdbc:odbc:DNS");

Upvotes: 1

Arjun Abhynav
Arjun Abhynav

Reputation: 543

We cannot create any object for any interface. But it is possible to assign a class object which is implementing that interface to the reference variable of that interface. Here con is a reference variable to that interface, and DriverManager.getConnection() returns a class object which implements the Connection interface.

Upvotes: 2

Related Questions