Java Reference
In-Depth Information
name a static variable of a static inner class within the outer class, just preface the static
variable name with the name of the inner class and a dot.
Static Inner Class
A
static
inner class is one that is not associated with an object of the outer class. It is
indicated by including the modifier
static
in its class heading.
Self-Test Exercises
24. Can you have a static method in a nonstatic inner class?
25. Can you have a nonstatic method in a static inner class?
Public Inner Classes
If an inner class is marked with the
public
modifier instead of the
private
modifier,
then it can be used in all the ways we discussed so far, but it can also be used outside of
the outer class.
The way that you create an object of the inner class outside of the outer class is a bit
different for static and nonstatic inner classes. We consider the case of a nonstatic inner
class first. When creating an object of a nonstatic inner class, you need to keep in mind
that every object of the nonstatic inner class is associated with some object of the outer
class. To put it another way, to create an object of the inner class, you must start with
an object of the outer class. This has to be true, because an object of the inner class may
invoke a method of the outer class or reference an instance variable of the outer class,
and you cannot have an instance variable of the outer class unless you have an object of
the outer class.
For example, if you change the class
Money
in Display 13.9 from private to public,
so that the class definition begins
public
inner
class
public class
BankAccount
{
public class
Money
then you can use an object of the nonstatic inner class
Money
outside of the class
BankAccount
as illustrated by the following:
BankAccount account =
new
BankAccount();
BankAccount.Money amount =
account.
new
Money("41.99");
System.out.println(amount.getAmount());
This code produces the output
41.99