Using Inner Classes
Problem
You need to write a private class, or a class to be used in one other class at the most.
Solution
Use a non-public class or an inner class.
Discussion
A non-public class can be written as part of another class’s source file, but is not included inside that class. An inner class is Java terminology for a class defined inside another class. Inner classes were first popularized with the advent of JDK 1.1 for use as event handlers for GUI applications (see Section 13.5), but they have a much wider application.
Inner classes can, in fact, be constructed in several contexts. An
inner class defined as a member of a class can be instantiated
anywhere in that class. An inner class defined inside a method can
only be referred to later in the same method. Inner classes can also
be named or anonymous. A
named inner class has a full name that
is compiler-dependent; the standard JVM uses a name like
MainClass$InnerClass.class
for the resulting file.
An anonymous inner class, similarly, has a compiler-dependent name;
the JVM uses MainClass$1.class
,
MainClass$2.class
, and so on.
These classes cannot be instantiated in any other context; any
explicit attempt to refer to, say,
OtherMainClass$InnerClass
, will be caught at
compile time.
import java.awt.event.*; import javax.swing.*; public class AllClasses { /** Inner class can be used anywhere in this file */ public class Data { int x; int y; } public void getResults( ) { JButton b = new JButton("Press me"); b.addActionListener(new ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.