Meaningless Drivel is fun!*
The moose likes Cattle Drive and the fly likes JDBC Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "JDBC Interfaces" Watch "JDBC Interfaces" New topic
Author

JDBC Interfaces

jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
I've not had any real experience creating interface objects, so I might just be having a brain hiccup here.
In the example Test and TestServlet, there are three interfaces that have objects created:

I can see that you aren't instantiating an object of the interface with new, which doesn't work because interfaces are abstract. However, you still have an object of this interface, so that's a little weird.
The other thing I don't get is how you can call methods on these "objects", and pass parameters to the methods, without having overriden these methods. Since interface methods can't have bodies to them, where the heck is the code coming from? Is it all coming from the Driver object you create? That also is a bit weird, since you never put the object that is returned from Class.forName("org.gjt.mm.mysql.Driver").newInstance() into a reference.
If these weren't interfaces I think I could follow along with this better, but I have always used interfaces in the context of them being implemented and methods being overriden, not working with direct "objects" of a interface, which I didn't think you could have (an object that implements an interface yes, an object directly from an interface, no).
Anyone care to shed some light?
Thanks!
Jason

[This message has been edited by jason adam (edited August 03, 2001).]
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Ok, I answered my own question. If you don't have it, download Jad, it's a Java decompiler, and look over the code for the classes in mySQL, it is very informative about what is going on in the code.
Jason
Lance Finney
Ranch Hand

Joined: Apr 26, 2001
Posts: 133
Where can I get jad?
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
It decompiles to a .jad file. You can set Windows (assuming you are using Windows) to use Notepad, or whatever, to open .jad files and you've got the code.
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Ok, I answered my own question. If you don't have it, download Jad, it's a Java decompiler, and look over the code for the classes in mySQL, it is very informative about what is going on in the code.

Ok, I didn't answer my own question. If you read through their classes, they have public classes that are named the same as the java.sql interfaces, so I thought the code was just creating an object of those classes. However, the code does not import in mysql's class files, so you can't be creating objects of these classes, right?
Anyone know what exactly is happening here?
Jason
Johannes de Jong
tumbleweed
Bartender

Joined: Jan 27, 2001
Posts: 5089
I'll try and look into it next week, Jason. Sorry busy weekend
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1757
    
    3
Anyone care to shed some light?

I'll take a shot at this.
There are a couple of issues causing confusion I think: using interfaces in general, the use of "new" with interfaces, and the specific interfaces in the JDBC code.
In the example Test and TestServlet, there are three interfaces that have objects created:
<snip>
I can see that you aren't instantiating an object of the interface with new, which doesn't work because interfaces are abstract. However, you still have an object of this interface, so that's a little weird.
<snip>
...not working with direct "objects" of a interface, which I didn't think you could have...

In Java there's no such thing as an "object of an interface" or suchlike. Objects are instances of classes. Now it's possible that a given class may implement any number of interfaces. If you create an object of such a class, you have just that -- an object that is of the type of that class.
Reference variables in Java can, however, have the type of a either a class or an interface. A reference variable whose type is that of a class points to an object that is an instance of that class (or to an instance of a subclass of that class, or to null). A reference variable whose type is that of an interface points to an object that is an instance of a class that implements that interface (or to an instance of a subclass of that class, or to null).
Take an example from the Java API. Here's the signature for the class ArrayList.
public class ArrayList extends AbstractList implements List, Cloneable,
java.io.Serializable
One way of creating an ArrayList object is like this:
ArrayList myStuff = new ArrayList() ;
Here myStuff is a reference variable of type "ArrayList" and it points to an object that is an instance of the class "ArrayList".
Another way of creating an ArrayList object is like this:
List myStuff = new ArrayList() ;
Here myStuff is a reference variable of type "List" (which is an interface) and it points to an object that is an instance of the class "ArrayList," which implements the List interface. The object is still an ArrayList, but we can get to it only through methods defined in List. (The code that gets executed is the code that's defined in the class for the actual type of the object.)
You can do this sort of thing because, as you can see from the definition of ArrayList, it implements the interface List, which means that it has implementations of all the methods called for by the List interface. (See previous discussions on interfaces and casting.)
Now, the next question is why would you want to do this sort of thing. In general it's because you need an object that does what a List does but you don't particularly care what specific class the object is that will get the job done, you care only that the object fulfills the contract spelled out in the List interface.
(Maybe you'll later need to change the code to use a LinkedList instead of an ArrayList. Maybe you're sending myStuff to a method that takes any List as a parameter. Etc.)
Note you could also get instances of ArrayList with references of type Cloneable or Serializable, if you had a need for that:
Cloneable c = new ArrayList() ;
Serializable s = new ArrayList() ;

Now on to the use of the "new" keyword with interfaces.
Consider the following interface. Ignore that it doesn't have any methods.
interface Michael
{
}
Consider the following two lines of code. What's the difference?
Michael m = new Michael() ;
Michael mm = new Michael() {} ;
Consider them again for a second (it's a bit of a trick question).
The trick is that the first line is not valid Java code and the second is, but it does something that may be surprising, depending on your comfort level with interfaces.
The first line declares a reference variable m of type "Michael" -- which is perfectly OK. But you get into trouble with new Michael() because "Michael" is an interface. By definition, you can't create an instance of an interface. The compiler shrieks:
C:\Michael\javaranch\projects\Interfaces\TestMichael.java:10: Michael is abstract; cannot be instantiated
Michael m = new Michael() ;
^
1 error
Tool completed with exit code 1
The second line also declares a reference variable (mm) of type "Michael" -- again, which is perfectly OK. Then there's the cryptic part
new Michael() {} ;
This is a special syntax that Java supports for creating anonymous classes that implement (a single?) interface. This code does two things: (1) it defines an anonymous class "on the fly," so to speak, that extends Object and implements Michael, and (2) it creates an object that is an instance of that class. (Then in our case points the reference variable mm to that object.)
You can think of the code
Michael mm = new Michael() {} ;
as getting compiled to something like
private class AnonymousClass extends Object implements Michael
{
}
Michael mm = new AnonymousClass() ;
Only you don't have the clutter of introducing a new class name in the anonymous version.
If you run this example you can see what I'm talking about:

Compiling this example results in 3 class files, 2 of which are "anonymous" within Java source code:
TestMichael.class
TestMichael$1.class
TestMichael$2.class
And running this example gives the following expected results:
TestMichael$1
TestMichael$2
Note that in the code at (1) you still have the handle "mm" in the scope of the main() method, so you can further manipulate this object if you want. However, at (2) when you define your anonymous subclass of Object that implements Michael, create an instance, and pass it as a parameter to perform() all in one shot, there's no longer any way of getting to that object within main().
I think you mentioned at some point, Jason, that you're familiar with using AWT and event interfaces. My code above at (2) is doing the same kind of thing as

I hope all this didn't muddy the waters too much. The point of it all is that there does exist a very specialized use of "new" with interfaces. But that doesn't change the fact that objects are instances of classes (or that reference variables have the type of either classes or interfaces.) When you wrote the bit about using new versus not using new and class versus interfaces, I wasn't sure that you had it all straight.

Now, on to the JDBC stuff.
I've installed mySQL and looked at the JDBC assignments, but haven't started working on them yet, so everything I'm about to write is just what I've surmised from looking at the API and source code.

Yes, Connection, Statement, and ResultSet are all interfaces. The reference variables con, statement, and rs are of type Connection, Statement, and ResultSet, respectively. (Remember, reference variables can have the type of an interface.) con points to an object that is an instance of a class that implements Connection. statement points to an object that is an instance of a class that implements Statement. rs points to an object that is an instance of a class that implements ResultSet.
What are the classes of these objects? To a certain degree, as a client of these classes, why should you care? (Yeah, I know as students of the language we're interested in such things.)
That's the beauty of interfaces. When you call DriverManager.getConnection( "jdbc:mysql://localhost/soup" ), it returns some object that is an instance of some class that implements the Connection interface. In a sense that's all you need to know to use it. You can then assign that object to con, and then call any method defined in the Connection interface on that object. The Connection interface defines a method Statement createStatement(). When you call con.createStatement() the code that gets executed is from con's class (whatever that may be) (if con's class directly implements Connection). createStatement() returns some object that is an instance of some class that implements the Statement interface. Etc.
If you're curious as to the exact class of these objects, just add the following code:
System.out.println( con.getClass().getName() ) ;
System.out.println( statement.getClass().getName() ) ;
System.out.println( rs.getClass().getName() ) ;
I'm taking a little shot in the dark here, but I think what you'll get is that con is of an an anonymous class in the org.gjt.mm.mysql package.
DriverManager maintains a Vector (think ArrayList) of objects that implement the Driver interface:
(Line 554 of DriverManager.java
private static java.util.Vector drivers = new java.util.Vector();
This, presumably, is a list of all the drivers that have loaded themselves and registered themselves with DriverManager by calling DriverManager.registerDriver( this ) somewhere in their code.
When you call DriverManager.getConnection( "jdbc:mysql://localhost/soup" ) eventually the private method getConnection() defined at line 488 gets called. Lines 506-521 -- cycle through the Vector looking to see if the String you passed in represents a registered driver. If so, it calls connect() on that driver and the driver returns an object that is an instance of a class that implements Connection.
What kind of stuff are you importing into this program. I think you'll find all your mystery objects in the stuff that sets up the mySQL drivers.

I hope I haven't added to the confusion.
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Thanks Mike
Yeah, after reading through all of the classes and interfaces that were being used here, I started to realize that I was looking over the fact that just because you have an interface reference doesn't mean your object is an interface... because you can't have an object of an interface. I was looking over one of the wonders of inheritance that I have been so used to using, that when you implement an interface, that class can be used where ever the interface is needed.
I agree, I don't need to know what is happening behind the scenes, and the more I dig into the actual source code, the more I start to get pulled off in other directions that I probably shouldn't be concerned with right now. Later on, when I have a better grasp, yes, right now, just worry about the implementation side. As you said, as students, very hard lesson to learn sometimes
Now that I have a fairly good understanding of that, the only thing that I still don't quite grasp is the line Class.forName("org.gjt.mm.mysql.Driver").newInstance() As you pipe through, forName() initializes the Driver class, and then newInstance() returns an Object of the Driver class, same as if by using new. Where does this Object go? In examples of these methods I have seen, they are always used with an identifier.

[This message has been edited by jason adam (edited August 04, 2001).]
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Ah, reading through Professional Java Server Programming J2EE Edition by Wrox (if you don't have it, I highly recommend it), it discusses this very issue. Basically, that line loads the driver into the system properties, and DriverManager then uses the static getConnection() method to search for a suitable driver. I haven't done the test you recommended Michael, but I think you are right about the anonymous class part. Once I get mySql loaded here at home, I'll give it a shot and let you know what I come up with
Thanks again,
Jason
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Ok, after doing the test you suggested Michael, and looking over the code again, found out my initial thought earlier about it using mySQL's classes named Connection, Statement, and ResultSet that implement the respective interfaces was correct, though it's used in a different way than I had thought. I'll figure this driver stuff out yet!
If your interested, the classes are located in org.gjt.mm.mysql.jdbc2
Well now, mystery solved, case closed. Danke for the help Michael!
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9053
    
  12
Thanks for the very good explanation, Michael.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Pauline McNamara
Sheriff

Joined: Jan 19, 2001
Posts: 4012
    
    6
Just read through this last night - you have a gift for explaining clearly, Michael. Even though I'm not yet writing code like this, I'm able to follow and appreciate the ideas.
Now another question on a more general level: using interfaces this way (instantiating objects with an interface type) - is this what is meant by "programming to an interface"?
Thanks,
Pauline

[This message has been edited by Pauline McNamara (edited August 07, 2001).]
Johannes de Jong
tumbleweed
Bartender

Joined: Jan 27, 2001
Posts: 5089
Fantastic Micheal , thank you !!!
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
I know, my only two comments to Michael are:
A) What books have you been reading, because I want them!
B) When are you going to write your own, cause I want it!
Johannes de Jong
tumbleweed
Bartender

Joined: Jan 27, 2001
Posts: 5089
You beat me to the punch Jason
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1757
    
    3
Originally posted by jason adam:
What books have you been reading, because I want them!

For general Java I like Bruce Eckel's Thinking in Java, although I haven't updated to the second edition yet.
There's no substitute for the Java API (and source code). I imagine some day I'll have to take a look at the Java Language Specification. I've always been meaning to work through the Sun Java Tutorial, but just haven't had the time.
I've already mentioned Design Patterns and Refactoring: Improving the Design of Existing Code. Martin Fowler has a great companion website to his book : Refactoring has made a profound impact on how I write code (Java and otherwise). See here for my post on this book. I actually typed out and worked through most of the examples in the book. I was just starting to do the same for the "missing chapter" from his book (it's on the website) when the whole assignment log automation project came along, so that's on hold.
(I'm kind of interested in "lightweight processes" such as test-first design and extreme programminng. See the links for further info. I have no experience with this, but I have played around a little with JUnit. Part of my interest in such "radical" approaches comes from the main thing I dislike about my current job -- adherence to a cumbersome methodology.)
After all the time I spent with the source code of the Java collections classes, I became quite a fan of Josh Bloch, who wrote all that stuff. I just recently picked up his new book Effective Java. So far it's been pretty interesting. He has a few opinions and recommendations that go against other advice I've read. That's should make for interesting reading.
I've started to prepare for the certification exam, so when I chose a prep book, I used the "anything by Addison-Wesley publishers" rule of picking an OO text. (Design Patterns, Refactoring, and Effective Java are all published by Addison-Wesley.) That would be A Programmer's Guide to Java Certification by Mughal and Rasmussen. So far I've been please with that one too.
The Pragmatic Programmer was a good read. A lot of stuff to think about in there.
I've also read much of the Grady Booch tome, Object-Oriented Analysis and Design With Applications, which is considered a classic text on OO design. Checked that one out of the library. I understand a 3rd edition is in the works.
On Usenet, I scan the comp.lang.java.programmer group. A lot of the discussion is over my head, but it's still a useful exercise.
I haven't taken full advantage of the other JavaRanch forums yet. I've stuck mainly to the Cattle Drive.
On the web, Roedy Green's Java & Internet Glossary is a great resource. That a site worth spending some time at. Read the section on How to Write Unmaintainable Code when you're in the mood for a smile.
[This message has been edited by Michael Matola (edited August 10, 2001).]
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1757
    
    3
Originally posted by Pauline McNamara:
Now another question on a more general level: using interfaces this way (instantiating objects with an interface type) - is this what is meant by "programming to an interface"?

Yes, I believe so. But one caveat -- the idea of programming to an interface predates Java. The Java designers just decided to use that common terminology for a specific language feature.
Design patterns, which is perhaps the source of the original advice "Program to an interface, not an implementation," uses "interface" and "abstract class" fairly interchangeably (the examples in that book are in C++ and Smalltalk, which apparently don't make the same distinction that Java does). Interfaces and abstract classes are slightly different things in Java, but the idea is still the same.
Pauline McNamara
Sheriff

Joined: Jan 19, 2001
Posts: 4012
    
    6
Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JDBC Interfaces