I’m loving Java

Well, I’ve been working with GWT for a while now on the calendar project. I still don’t know Java all that well, but it’s close enough to C++ that I get by, learning as I go.  I find that it takes me twice as long as it should to do something the first time I do it, but then half the time it would have taken in C++ in most cases on subsequent attempts.

One of the things I’ve found that I love about Java is how its callbacks work.  In C/C++, callbacks are implemented as function pointers.  This works ok, but the whole thing feels like a kludge.  No matter what the situation, you get the following function signature:

void funtionName(void* param);

It’s sort of like labeling a pair of stretch pants as being “one size fits all”; it could more accurately be described as “one size fits several”.  With Java, you don’t have callbacks built into the language by that name; what most people do instead is use an object that implements a particular interface.  An interface in Java is a set of methods that any “implementing” class must define.  That way, the code that uses the callback knows it can call randomObject.agreedUponFunction().  That gives a lot flexibility.

That’s not even my favorite part.  Check this out:

import java.io.*;

class CallBack {
    public interface myInterface {
        public void theCall();

    public static void main(String[] args) {
        myInterface bubba = new myInterface() {
            public void theCall() {
                System.out.println("Bubba's calling!");

        final Boolean someSwitch = false;
        final myInterface finalBubba = bubba;

        myInterface jimmy = new myInterface() {
            public void theCall() {
                System.out.println("Jimmy's calling!");

                if(someSwitch) {
                } else {


Jimmy's calling!
Bubba's calling!

Notice something strange?  Yep, I have referenced variables from outside the scope of the function definition for Jimmy.theCall().  This is an amazing convenience if the flow of your callback needs to change depending on external conditions; the only catch that I’ve noticed is that any outside variables you reference must be declared final.  As I have demonstrated here, though, it’s simple to take a non-final variable and make a final one out of it. I don’t know how Java handles all this, but I like it!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: