Java Reference
In-Depth Information
For example,
canvas
is defined in
ControlCircle
in Listing 16.3 (line 8). It can be
referenced in the inner class
EnlargeListener
in line 34.
An inner class can be defined with a visibility modifier subject to the same visibility
rules applied to a member of the class.
■
An inner class can be defined as
static
. A
static
inner class can be accessed
using the outer class name. A
static
inner class cannot access nonstatic members
of the outer class.
■
Objects of an inner class are often created in the outer class. But you can also create
an object of an inner class from another class. If the inner class is nonstatic, you must
first create an instance of the outer class, then use the following syntax to create an
object for the inner class:
OuterClass.InnerClass innerObject = outerObject.
new
InnerClass();
■
If the inner class is static, use the following syntax to create an object for it:
OuterClass.InnerClass innerObject =
new
OuterClass.InnerClass();
■
A simple use of inner classes is to combine dependent classes into a primary class. This reduces
the number of source files. It also makes class files easy to organize, since they are all named with
the primary class as the prefix. For example, rather than creating the two source files
Test.java
and
A.java
in Figure 16.9a, you can merge class
A
into class
Test
and create just one source file,
Test.java
in Figure 16.9b. The resulting class files are
Test.class
and
Test$A.class
.
Another practical use of inner classes is to avoid class-naming conflicts. Two versions of
CirclePanel
are defined in Listings 16.2 and 16.3. You can define them as inner classes to
avoid a conflict.
A listener class is designed specifically to create a listener object for a GUI component
(e.g., a button). The listener class will not be shared by other applications and therefore is
appropriate to be defined inside the frame class as an inner class.
16.7
Can an inner class be used in a class other than the class in which it nests?
✓
✓
Check
16.8
Can the modifiers
public
,
private
, and
static
be used for inner classes?
Point
An
anonymous inner class
is an inner class without a name. It combines defining an
inner class and creating an instance of the class into one step.
Key
Point
Inner-class listeners can be shortened using
anonymous inner classes
. The inner class in
Listing 16.3 can be replaced by an anonymous inner class as shown below.
anonymous inner class
public
ControlCircle() {
// Omitted
public
ControlCircle() {
// Omitted
jbtEnlarge.addActionListener(
new
jbtEnl
arge.addActionListene
r(
new cl
ass
Enlarg
eListener
implements
ActionListener
EnlargeListener()
);
()
}
{
@Override
public void
actionPerformed(ActionEvent e) {
canvas
.enlarge();
class
EnlargeListener
implements
ActionListener {
@Override
public void
actionPerformed(ActionEvent e) {
canvas
.enlarge();
}
});
}
}
}
(b) Anonymous inner class
(a) Inner class
EnlargeListener