Java Reference
In-Depth Information
In other words, a static nested class is not really much different than a top-level class
except for a few subtle benefi ts:
The nesting creates a type of namespace. To denote a nested class from outside its
enclosing class, the nested class is prefixed with the name of the enclosing class (similar
to how static fields and methods are accessed).
Access to the nested class can be controlled by an access specifier. For example, a
nested class declared as
private
can only be used within its enclosing class, in effect
hiding it from any other classes.
The enclosing class has access to the fields and methods of the nested class, even the
private
ones.
Let's look at an example. The following
Box
class is nested within
Shipment
:
1. import java.awt.Dimension;
2.
3. public class Shipment {
4. public static class Box {
5. public Dimension dimension;
6. public int depth;
7.
8. public Box(Dimension d, int x) {
9. dimension = d;
10. depth = x;
11. }
12.
13. public int getVolume() {
14. return dimension.height * dimension.width * depth;
15. }
16. }
17.
18. public Box box;
19.}
Even though
Box
is defi ned inside
Shipment
, because
Box
is
static
it can be used like
any other top-level class. The syntax for referring to
Box
outside of
Shipment
is
Shipment
.Box
. The following
Shoe
class declares a fi eld of type
Shipment.Box
and initializes the fi eld
in its constructor. See if you can determine the output of running the
main
method in
Shoe
:
1. import java.awt.Dimension;
2.
3. public class Shoe {
4. public Shipment.Box box;
5.
Search WWH ::
Custom Search