What Value Does Generics Add?
You may think Java doesn't really need a mechanism of this type. After all, without generics, you could just write
so that it sends and receives objects of type
, and add in a little bit of casting to get the objects to by the type you need. But generics provides two useful features.
First and foremost, generics offers better compile-time type checking. In a sense, a cast is just a run-time type check. Since it happens at run time, it also could fail at run-time. With generics, the type casting is implicit in the instantiation you are using
Mailbox<Whatever>and it's done at compile-time. By using a particular instantiation, you are in essence saying this
Object is really going to be a
String, and the compiler will verify whether this is consistent with everything else going on in the program.
Secondly, generics provides convenience. Casting can be irritatingyou can feel like you're telling the compiler something that should be obvious. It also makes code harder to read, since it can turn a simple assignment (or parameter-pass) into a more complicated expression. With generics, casting just goes away. This might sound like a small thing, but try generics for a while and then go back to castingyou'll miss generics.
The NMF Example
NMF is, as previously mentioned, a simple, extensible networked multimedia framework. Put another way, it's a glorified chat with graphics. The NMF client contains two sub-clients: a chat window and a shared whiteboard window. The chat window is what you would expect: type something in the text field and this sub-client sends the message to all users. The shared whiteboard is like the chat, but for drawing: draw some lines and this sub-client sends the drawing to all users. Figure 1 shows these windows in the NMF client.
The nice thing about NMF is that it is extensible. If you want to create more sub-clients, you can. The application Figure 1
shows is only one way of setting things up. You can easily create an interface with more clients, arranged any way you want.
To run the program, you'll need to run the server like so:
% java Server 5000
5000 is the port number on which you want the server to listen. You can change this value, but you'll have to change the port number in
sample.html as well.
Sample.html is the client-side applet file. You can run the client by visiting this HTML page in your browser, or by running appletviewer like this:
% appletviewer sample.html
Either way, you should see a window like the one in Figure 1.
Now that you have the program running, the following sections describe how it works and how it uses generics.