Wednesday, August 11, 2010

Java's Inner Classes: The Keys to the Kingdom

In my two most recent code examples I've used inner classes in the program.

Java Video Game Programming: Game Logic

A Simple Java Video Game Kernel

An inner class is a Java class that's defined inside another class. In both the examples above, I have a class called VGKernel, which is the class that implements the video game kernel. Inside that class, I define other classes. This has a special effect on the relationship between those classes and VGKernel.

Normally, our objects are encapsulated, that is, their members (variables and methods) are inaccessible to other classes unless they've been marked as public, and in those cases we take care to make sure that the object can't be messed up using those public members.

Some things in Java don't work very well with the encapsulation. Graphics and Threads are two of them. Fortunately, there's a way around the encapsulation. It lets one object access all the members of another object as if it owned them.

The downside is that this can be a dangerous coding practice, like global variables (check out the sort of problems  JavaScript's had with security, if you want to know why global variables are a problem.) Your inner class has complete control over the outer class. Root access, keys to the kingdom. It could wear the outer class like the alien guy wore the redneck's skin in Men in Black.

If used well inner classes solve a multitude of problems. In the case of the two versions of VGKernel, it solves the problem of the ball being able to access the graphical context (at present, the Ball class doesn't really need to, I'll admit, but we'll see more of why it does this as the code develops in future articles), and it allows VGTimerTask to access the methods of VGKernel.

The Java Tutorial has a pretty good section on inner classes, as one type of nested class.
StumbleUpon