On Java inner classes and whatnot


Classic Java logo

A few weeks ago I discussed the different ways to include multiple classes in one file, and one of the comments questioned my use of a class within a class. Apparently when they tried to do it in earlier versions of Java all they got in return was grief. I could say something there about swearing being the common language of all programmers but I'll leave it at that :).

From what I can tell, so called inner classes were introduced in Java 5, and they allow you to do some pretty cool stuff. By having an inner class defined within an outer class:

  • the inner class can access the data members of the outer class without the need for setter and getter methods
  • tidyness and encapsulation es ist gut so!
  • if you start getting into using C++’eque <T> object types (something I’m learning now) the outer and inner classes automatically share them (which they need to anyway)
  • of lesser importance, you only need to give the Java compiler one file to compile two or more related classes, and you only need to work on the one file

When you compile a java class with inner classes, the resulting compiled bytecode class file whatsits (to use the technical terminology) are divided into outer classes and inner classes with a dollar sign:

% javac OuterClass.java
% ls -l
==> OuterClass.class
==> OuterClass$innerClass.class
% echo Grilled Cheese Sandwich
==> Grilled Cheese Sandwich

My Java linked list stack post shows how a outer link list class uses an inner Node class if you want to check it out. Another example is the Iterator class which belongs to Java's new and very nice to use lists that implement the List interface, other things I'll be blogging about soon once I've had a chance to play around with them more.

Personally I can already see how these could be abused, but I guess as with any great power comes great responsibility, and with any blog post comes the need for a cliché apparently!

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.