Java nested and inner classes are formally defined in chapter 8 of the Java Language Specification (https://java.sun.com/docs/books/jls/third_edition/html/classes.html). The terms used there can be somewhat confusing – in general, what we are talking about here are “nested classes” (or interfaces). These are divided into “static nested classes” and “inner classes”. Static nested classes are bound to a class, not to an instance, and therefore do not have access to the instance variables of the enclosing class. If nested classes are bound to the instance of a class, they are called “inner classes”. For inner classes, again various sub types exists: (simple) inner classes, local inner classes and anonymous inner classes.
To have a closer look to Java nested classes, let’s first define an interface with one method which allows to print a String:
package littletux.net.innerclass; public interface Printer { void printString(String value); }
Then, we define a class which is using the Printer interface. The class allows setting a Printer and then allows us to print Strings using the previously set printer (note that there is no error handling implemented):
package littletux.net.innerclass; public class PrintManager { private Printer printer; public void setPrinter(Printer p) { printer = p; } public void print(String s) { printer.printString(s); } }
Now, let’s have a look at the various nested class types and how we can use them with the small framework defined above. Note that the Java compiler creates separate class files for nested classes, according to a special naming scheme. The name of the created class files is shown inside comments in the source code within the next sections.