All of the classes we’ve seen so far in this book have been top-level, “freestanding” classes declared at the file and package level. But classes in Java can actually be declared at any level of scope, within any set of curly braces (i.e., almost anywhere that you could put any other Java statement). These inner classes belong to another class or method as a variable would and may have their visibility limited to its scope in the same way. Inner classes are a useful and aesthetically pleasing facility for structuring code. Their cousins, anonymous inner classes, are an even more powerful shorthand that make it seem as if you can create new kinds of objects dynamically within Java’s statically typed environment. In Java, anonymous inner classes play part of the role of closures in other languages, giving the effect of handling state and behavior independently of classes.
However, as we delve into their inner workings, we’ll see that inner classes are not quite as aesthetically pleasing or dynamic as they seem. Inner classes are pure syntactic sugar; they are not supported by the VM and are instead mapped to regular Java classes by the compiler. As a programmer, you may never need be aware of this; you can simply rely on inner classes like any other language construct. However, you should know a little about how inner classes work to better understand the compiled code and a few potential side effects.
Inner classes are essentially nested classes, for example:
Class
Animal
{
Class
Brain
{
...
}
}
Here, the class Brain
is an inner
class: it is a class declared inside the scope of class Animal
. Although the details of what that means
require a bit of explanation, we’ll start by saying that Java tries to
make the meaning, as much as possible, the same as for the other members
(methods and variables) living at that level of scope. For example, let’s
add a method to the Animal
class:
Class
Animal
{
Class
Brain
{
...
}
void
performBehavior
()
{
...
}
}
Both the inner class Brain
and the method performBehavior()
are within the scope of
Animal
. Therefore, anywhere within
Animal
, we can refer to Brain
and performBehavior()
directly, by name. Within
Animal
, we can call the constructor for
Brain
(new
Brain()
) to get a Brain
object or invoke performBehavior()
to
carry out that method’s function. But neither Brain
nor performBehavior()
are generally accessible
outside of the class Animal
without
some additional qualification.
Within the body of the inner Brain
class and the body of the performBehavior()
method, we have direct access
to all the other methods and variables of the Animal
class. So, just as the performBehavior()
method could work with the
Brain
class and create instances of
Brain
, methods within the Brain
class can invoke the performBehavior()
method of Animal
as well as work with any other methods
and variables declared in Animal
. The
Brain
class “sees” all of the methods
and variables of the Animal
class
directly in its scope.
That last bit has important consequences. From within Brain
, we can invoke the method performBehavior()
; that is, from within an
instance of Brain
, we can invoke the
performBehavior()
method of an instance
of Animal
. Well, which instance of
Animal
? If we have several Animal
objects around (say, a few Cat
s and Dog
s), we need to know whose performBehavior()
method we are calling. What
does it mean for a class definition to be “inside” another class
definition? The answer is that a Brain
object always lives within a single instance of Animal
: the one that it was told about when it
was created. We’ll call the object that contains any instance of Brain
its enclosing
instance.
A Brain
object cannot live
outside of an enclosing instance of an Animal
object. Anywhere you see an instance of
Brain
, it will be tethered to an
instance of Animal
. Although it is
possible to construct a Brain
object
from elsewhere (i.e., another class), Brain
always requires an enclosing instance of
Animal
to “hold” it. We’ll also say now
that if Brain
is to be referred to from
outside of Animal
, it acts something
like an Animal.Brain
class. And just as
with the performBehavior()
method,
modifiers can be applied to restrict its visibility. All of the usual
visibility modifiers apply, and inner classes can also be declared
static
, as we’ll discuss later.
We’ve said that within the Animal
class, we can construct a Brain
in the
ordinary way, using new Brain()
, for
example. Although we’d probably never find a need to do it, we can also
construct an instance of Brain
from
outside the class by referencing an instance of Animal
. To do this requires that the inner class
Brain
be accessible and that we use a
special form of the new
operator designed
just for inner classes:
Animal
monkey
=
new
Animal
();
Animal
.
Brain
monkeyBrain
=
monkey
.
new
Brain
();
Here, the Animal
instance
monkey
is used to qualify the new
operator on Brain
. Again, this is not a very common thing to
do and you can probably just forget that we said anything about it. Static
inner classes are more useful. We’ll talk about them a bit later.
A particularly important use of inner classes is to make
adapter classes. An adapter class is a “helper”
class that ties one class to another in a very specific way. Using
adapter classes, you can write your classes more naturally, without
having to anticipate every conceivable user’s needs in advance. Instead,
you provide adapter classes that marry your class to a particular
interface. As an example, let’s say that we have an Employee
List
object:
public
class
EmployeeList
{
private
Employee
[]
employees
=
...
;
...
}
EmployeeList
holds information
about a set of employees. Let’s say that we would like to have EmployeeList
provide its elements via an
iterator. An iterator is a simple, standard interface to a sequence of
objects. The java.util.Iterator
interface has several methods:
public
interface
Iterator
{
boolean
hasNext
();
Object
next
();
void
remove
();
}
It lets us step through its elements, asking for the next one and
testing to see if more remain. The iterator is a good candidate for an
adapter class because it is an interface that our EmployeeList
can’t readily implement itself.
Why can’t the list implement the iterator directly? Because an iterator
is a “one-way,” disposable view of our data. It isn’t intended to be
reset and used again. It may also be necessary for there to be multiple
iterators walking through the list at different points. We must,
therefore, keep the iterator implementation separate from the EmployeeList
itself. This is crying out for a
simple class to provide the iterator capability. But what should that
class look like?
Before we knew about inner classes, our only recourse would have
been to make a new “top-level” class. We would probably feel obliged to
call it EmployeeListIterator
:
class
EmployeeListIterator
implements
Iterator
{
// lots of knowledge about EmployeeList
...
}
Here we have a comment representing the machinery that the
EmployeeListIterator
requires. Think
for just a second about what you’d have to do to implement that
machinery. The resulting class would be completely coupled to the
EmployeeList
and unusable in other
situations. Worse, in order to to function, it must have access to the
inner workings of EmployeeList
. We
would have to allow EmployeeListIterator
access to the private
array in EmployeeList
, exposing this
data more widely than it should be. This is less than ideal.
This sounds like a job for inner classes. We already said that
EmployeeListIterator
was useless
without an EmployeeList
; this sounds
a lot like the “lives inside” relationship we described earlier.
Furthermore, an inner class lets us avoid the encapsulation problem
because it can access all the members of its enclosing instance.
Therefore, if we use an inner class to implement the iterator, the array
employees
can remain private
, invisible outside the EmployeeList
. So let’s just shove that helper
class inside the scope of our EmployeeList
:
public
class
EmployeeList
{
private
Employee
[]
employees
=
...
;
...
class
Iterator
implements
java
.
util
.
Iterator
{
int
element
=
0
;
boolean
hasNext
()
{
return
element
<
employees
.
length
;
}
Object
next
()
{
if
(
hasNext
()
)
return
employees
[
element
++
];
else
throw
new
NoSuchElementException
();
}
void
remove
()
{
throw
new
UnsupportedOperationException
();
}
}
}
Now EmployeeList
can provide a
method like the following to let other classes work with the
list:
Iterator
getIterator
()
{
return
new
Iterator
();
}
One effect of the move is that we are free to be a little more
familiar in the naming of our iterator class. Since it is no longer a
top-level class, we can give it a name that is appropriate only within
the EmployeeList
. In this case, we’ve
named it Iterator
to emphasize what
it does, but we don’t need a name like EmployeeIterator
that shows the relationship
to the EmployeeList
class because
that’s implicit. We’ve also filled in the guts of the Iterator
class. As you can see, now that it is
inside the scope of EmployeeList
,
Iterator
has direct access to its
private members, so it can directly access the employees
array. This greatly simplifies the
code and maintains compile-time safety.
Before we move on, we should note that inner classes can have constructors, variables, and initializers, even though we didn’t need one in this example. They are, in all respects, real classes.
Inner classes may also be declared for “local” use within
the body of a method. Returning to the Animal
class, we can put Brain
inside the performBehavior()
method if we decide that the
class is useful only inside that method:
Class
Animal
{
void
performBehavior
()
{
Class
Brain
{
...
}
}
}
In this situation, the rules governing what Brain
can see are the same as in our earlier
example. The body of Brain
can see
anything in the scope of performBehavior()
and above it (in the body of
Animal
). This includes local
variables of performBehavior()
and
its arguments. But because of the fleeting nature of a method
invocation, there are a few limitations and additional restrictions, as
described in the following sections. If you are thinking that inner
classes within methods sounds arcane, bear with us until we talk about
anonymous inner classes, which are tremendously useful.
performBehavior()
is
a method, and method invocations have limited lifetimes. When they
exit, their local variables normally disappear into the abyss.
However, an instance of Brain
(like
any object created in the method) lives on as long as it is
referenced. Java must make sure that any local variables used by
instances of Brain
created within
an invocation of performBehavior()
also live on. Furthermore, all the instances of Brain
that we make within a single
invocation of performBehavior()
must see the same local variables. To accomplish this, the compiler
must be allowed to make copies of local variables. Thus, their values
cannot change once an inner class has seen them. This means that any
of the method’s local variables or arguments that are referenced by
the inner class must be declared final
. The final
modifier means that they are constant
once assigned. This is a little confusing and easy to forget, but the
compiler will graciously remind you. For example:
void
performBehavior
(
final
boolean
nocturnal
)
{
class
Brain
{
void
sleep
()
{
if
(
nocturnal
)
{
...
}
}
}
}
In this code snippet, the argument nocturnal
to the performBehavior()
method must be marked
final
so that it can be referenced
within the inner class Brain
. This
is just a technical limitation of how inner classes are implemented,
ensuring that it’s OK for the Brain
class to keep a copy of the value.
We mentioned earlier that the inner class Brain
of the class Animal
can, in some ways, be considered an
Animal.Brain
class—that is, it is
possible to work with a Brain
from
outside the Animal
class, using
just such a qualified name: Animal.Brain
. But as we described, given
that our Animal.Brain
class always
requires an instance of an Animal
as its enclosing instance, it’s not as common to work with them
directly in this way.
However, there is another situation in which we want to use
inner classes by name. An inner class that lives within the body of a
top-level class (not within a method or another inner class) can be
declared static
. For
example:
class
Animal
{
static
class
MigrationPattern
{
...
}
...
}
A static inner class such as this acts just like a new top-level
class called Animal.MigrationPattern
. We can use it just
like any other class, without regard to any enclosing instances.
Although this may seem strange, it is not inconsistent because a
static member never has an object instance associated with it. The
requirement that the inner class be defined directly inside a
top-level class ensures that an enclosing instance won’t be needed. If
we have permission, we can create an instance of the class using the
qualified name:
Animal
.
MigrationPattern
stlToSanFrancisco
=
new
Animal
.
MigrationPattern
();
As you see, the effect is that Animal
acts something like a minipackage,
holding the MigrationPattern
class.
Here, we have used the fully qualified name, but we could also import
it like any other class:
import
Animal.MigrationPattern
;
This statement enables us to refer to the class simply as
MigrationPattern
. We can use all
the standard visibility modifiers on inner classes, so a static inner
class can have private
, protected
, default
, or public
visibility.
Here’s another example. The Java 2D API uses static inner
classes to implement specialized shape classes (i.e., the java.awt.geom.Rectangle2D
class has two
inner classes, Float
and Double
, that implement two different
precisions). These shape classes are actually very simple subclasses;
it would have been sad to have to multiply the number of top-level
classes in that package by three to accommodate all of them. With
inner classes, we can bundle them with their respective
classes:
Rectangle2D
.
Float
rect
=
new
Rectangle2D
.
Float
();
Now we get to the best part. As a general rule, the more deeply encapsulated and limited in scope our classes are, the more freedom we have in naming them. We saw this in our earlier iterator example. This is not just a purely aesthetic issue. Naming is an important part of writing readable, maintainable code. We generally want to use the most concise, meaningful names possible. A corollary to this is that we prefer to avoid doling out names for purely ephemeral objects that are going to be used only once.
Anonymous inner classes are an extension of the syntax of the
new
operation. When
you create an anonymous inner class, you combine a class declaration
with the allocation of an instance of that class, effectively creating
a “one-time only” class and a class instance in one operation. After
the new
keyword, you specify either
the name of a class or an interface, followed by a class body. The
class body becomes an inner class, which either extends the specified
class or, in the case of an interface, is expected to implement the
interface. A single instance of the class is created and returned as
the value.
For example, we could do away with the declaration of the
Iterator
class in the EmployeeList
example by using an anonymous
inner class in the getIterator()
method:
Iterator
getIterator
()
{
return
new
Iterator
()
{
int
element
=
0
;
boolean
hasNext
()
{
return
element
<
employees
.
length
;
}
Object
next
()
{
if
(
hasNext
()
)
return
employees
[
element
++
];
else
throw
new
NoSuchElementException
();
}
void
remove
()
{
throw
new
UnsupportedOperationException
();
}
};
}
Here, we have simply moved the guts of Iterator
into the body of an anonymous inner
class. The call to new
implicitly
creates a class that implements the Iterator
interface and returns an instance
of the class as its result. Note the extent of the curly braces and
the semicolon at the end. The getIterator()
method contains a single
statement, the return
statement.
The previous example is a bit extreme and certainly does not
improve readability. Inner classes are best used when you want to
implement a few lines of code, but the verbiage and conspicuousness of
declaring a separate class detracts from the task at hand. Here’s a
better example. Suppose that we want to start a new thread to execute
the performBehavior()
method of our
Animal
:
new
Thread
()
{
public
void
run
()
{
performBehavior
();
}
}.
start
();
Here, we have gone over to the terse side. We’ve allocated and
started a new Thread
, using an
anonymous inner class that extends the Thread
class and invokes our performBehavior()
method in its run()
method. The effect is similar to using
a method pointer in some other language. However, the inner class
allows the compiler to check type consistency, which would be more
difficult (or impossible) with a true method pointer. At the same
time, our anonymous adapter class with its three lines of code is much
more efficient and readable than creating a new, top-level adapter
class named AnimalBehaviorThreadAdapter
.
While we’re getting a bit ahead of the story, anonymous adapter
classes are a perfect fit for event handling (which we cover fully in
Chapter 16). Skipping a lot of explanation,
let’s say you want the method handleClicks()
to be called whenever the
user clicks the mouse. You would write code such as:
addMouseListener
(
new
MouseInputAdapter
()
{
public
void
mouseClicked
(
MouseEvent
e
)
{
handleClicks
(
e
);
}
}
);
In this case, the anonymous class extends the MouseInputAdapter
class by overriding its mouseClicked()
method
to call our method. A lot is going on in a very small space, but the
result is clean, readable code. You assign method names that are
meaningful to you while allowing Java to do its job of type
checking.
Sometimes an inner class may want to get a handle on its “parent” enclosing instance. It might want to pass a reference to its parent or to refer to one of the parent’s variables or methods that has been hidden by one of its own. For example:
class
Animal
{
int
size
;
class
Brain
{
int
size
;
}
}
Here, as far as Brain
is
concerned, the variable size
in
Animal
is shadowed by its own
version.
Normally, an object refers to itself using the special this
reference (implicitly or explicitly).
But what is the meaning of this
for
an object with one or more enclosing instances? The answer is that an
inner class has multiple this
references. You can specify which this
you want by prefixing it with the name
of the class. For instance (no pun intended), we can get a reference
to our Animal
from within Brain
, like so:
class
Brain
{
Animal
ourAnimal
=
Animal
.
this
;
...
}
Similarly, we could refer to the size
variable in Animal
:
class
Brain
{
int
animalSize
=
Animal
.
this
.
size
;
...
}
Finally, let’s get our hands dirty and take a look at what’s really going on when we use an inner class. We’ve said that the compiler is doing all the things that we had hoped to forget about. Let’s see what’s actually happening. Try compiling this trivial example:
class
Animal
{
class
Brain
{
}
}
What you’ll find is that the compiler generates two .class files: Animal.class and Animal$Brain.class.
The second file is the class file for our inner class. Yes, as we feared, inner classes are really just compiler magic. The compiler has created the inner class for us as a normal, top-level class and named it by combining the class names with a dollar sign. The dollar sign is a valid character in class names, but is intended for use only by automated tools. (Please don’t start naming your classes with dollar signs.) Had our class been more deeply nested, the intervening inner class names would have been attached in the same way to generate a unique top-level name.
Now take a look at the class with the JDK’s javap
utility. Starting in Java 5.0, you can
refer to the inner class as Animal.Brain
, but in earlier versions of
Java, you may have to call the class by its real name, Animal$Brain
:
%
javap
'
Animal$Brain
'
class
Animal
$Brain
extends
java
.
lang
.
Object
{
Animal$Brain
(
Animal
);
}
On a Windows system, it’s not necessary to quote the argument, as we did on this Unix command line.
You’ll see that the compiler has given our inner class a
constructor that takes a reference to an Animal
as an argument. This is how the real
inner class gets the reference to its enclosing instance.
The worst thing about these additional class files is that you need to know they are there. Utilities such as jar don’t automatically find them; when you’re invoking such a utility, you need to specify these files explicitly or use a wildcard to find them:
%
jar
cvf
animal
.
jar
Animal
*
class
Given what we just saw—that the inner class really does exist as an automatically generated top-level class—how does it get access to private variables? The answer, unfortunately, is that the compiler is forced to break the encapsulation of your object and insert accessor methods so that the inner class can reach them. The accessor methods are given package-level access, so your object is still safe within its package walls, but it is conceivable that this difference could be meaningful if people were allowed to create new classes within your package.
The visibility modifiers on inner classes also have some
problems. Current implementations of the VM do not implement the
notion of a private
or protected
class within a package, so giving
your inner class anything other than public
or default visibility is only a
compile-time guarantee. It is difficult to conceive of how these
security issues could be abused, but it is interesting to note that
Java is straining a bit to stay within its original design.[19]
Get Learning Java, 4th Edition 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.