Java’s Inner Classes: The Keys to the Kingdom

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.
The downside is that this can be a dangerous coding practice, like global 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 needto, 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.

When should inner classes be used in Java?

Inner classes were introduced in version 1.1 of Java. Ever since they were introduced they inspired a lot of different opinions among people – but we won’t present any opinions here, just facts. Knowing when to use inner classes is very important, because using inner classes in the wrong situations can lead to code that’s difficult to understand and maintain.

Does an inner class violate encapsulation?

No, an inner class does not violate encapsulation because of the fact that an inner class is authored by the same person who created the outer class – so having an inner class was an intentional design decision.

Enter Your Comment

Your email address will not be published. Required fields are marked *