I understand how interfaces work in general but I am confused about a thing. I started learning about JDBC and I can’t understand this statement:
Connection conn = null; // set a reference pointing to nothing
Statement stmt = null;
PreparedStatement preparedStmt = null;
conn = DriverManager.getConnection('mysql/derby/other db', 'user', 'password');
//This is what I don't understand
stmt = conn.createStatement(); // Interface reference calling another interface's method
// Or this
preparedStmt = conn.preparedStatement("INSERT INTO db.table values (?, ?, ?, ?)";
I have a Statement interface reference pointing to another interface’s method Connection interface. Where is this method defined?
While you can have variables that are of interfaces types (e.g.
Connection,Statement, …), the actual objects at runtime need to be of some specific implementation type.For example
DriverMananger.getConnection()takes over the job of finding theConnectionimplementation that can handle the JDBC URL you provided.Let’s assume that it’s the fictional
MyDBConnectionclass (that implementsConnectionof course).Now your
connvariable holds a reference of to aMyDBConnection.When you call
createStatement()on that object, it’s actuallyMyDBConnection.createStatement()that gets executed. That method could look like this:After this, your
stmtvariable would hold a reference to aMyDBStatementobject.Remember: if any method promises to return something of type
A, it can equally well return something of a sub-type ofA(i.e. either a sub-class ofAor a class implementingA, ifAis an interface). In fact, whenAis an interface it has to return a class implementingA. Since a pureAobject can’t exist.