我创建了一个到 mysql 数据库的连接。下面是我的代码
package org;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DatabaseConn {
public static void main(String[] args) {
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
try {
String host = "jdbc:mysql://localhost:3306/sys";
String username = "root";
String password = "root";
Connection Con = DriverManager.getConnection(host, username, password);
Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );
System.out.println("Records:"+rs);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
我对类的接口(interface)实现的理解是,接口(interface)类型引用实现接口(interface)的类的对象。
但是当我调查上面代码中使用的以下代码片段时..
Connection Con = DriverManager.getConnection(host, username, password);
DriverManager.getConnection(host、username、password) 返回对象的引用(Connection 类型),但类 DriverManager 中未实现任何接口(interface)。谁能消除我的这个疑问..?或者我错过了什么?
下面的代码片段无法得到同样的结果
Statement SQL = Con.createStatement();
Con.createStatement() 应返回对实现 Statement 接口(interface)的对象的引用。但是这个 Connection 接口(interface)是由 ConnectionImpl 类实现的,其中的实现如下所示
public class ConnectionImpl
extends ConnectionPropertiesImpl
implements Connection {
public Statement createStatement()
throws SQLException
{
return createStatement(1003, 1007);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
{
checkClosed();
StatementImpl stmt = new StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
}
最佳答案
让我们一点一点地看一下:
DriverManager.getConnection(host, username, password)
returns a reference (of typeConnection
) to a object...
这是正确的。
...but no interface is implemented in class
DriverManager
.
这也是正确的。
您的解释缺少的是 DriverManager.getConnection()
不会返回对 DriverManager
的引用。它返回对不同类的对象的引用,该类确实实现了Connection
接口(interface)。
为了便于论证,我们假设有一个名为 MySqlConnection
的类:
class MySqlConnection implements Connection {
...
}
现在,DriverManager.getConnection()
很可能返回此类的实例:
class DriverManager {
public Connection getConnection(...) {
return new MySqlConnection(...);
}
}
希望这能解决问题。
关于java - 接口(interface)如何引用没有实现接口(interface)的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45659586/