createStatement method in jdbc
I have learned that Connection is an interface and we ca开发者_运维问答n define only method definition in interface. So how does this work:
....
Statement stmt = con.createStatement();
....
How does this method create a Statement object and return it?
Because a concrete implementation of the Connection
interface is been returned when you called getConnection()
. The interface just definies the method signatures. The concrete implementation contains the method implementations.
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection.getClass().getName()); // That's the name of the concrete implementation.
It's the JDBC driver which contains those concrete implementations. The JDBC API enables you to write Java code independent of the specific database server used. Whenever you switch of DB, you just have to switch the JDBC driver (and possibly also change the SQL statements whenever they contain DB-server specific SQL language, but not the Java code).
Have a look at this eg. The concept is similar to this eg.
public interface Human
{
public void run();
}
public class Man implements Human
{
public void run()
{
System.out.println("Man");
}
}
public class Main
{
public static void main(String s)
{
Human h= new Man();
h.run();
}
}
The output for this program will be Man
.
Now comparing this with your problem.
Connection con = DriverManager.getConnection(url, username, password)
,
con doesn't point to connection object because it is an interface, it points to some class which has definately inherited Connection
interface.
Now when you do this
Statement stmt = con.createStatement();
It does not call Connection
interface method, it calls con actual refered method.
So you don't even know what it will return plus stmt will definately point to class which
has inherited Statement
interface.
精彩评论