Java Reference
In-Depth Information
6. public Shoe() {
7. Dimension dim = new Dimension(6, 10);
8. box = new Shipment.Box(dim, 4);
9. }
10.
11. public static void main(String [] args) {
12. Shoe sandal = new Shoe();
13. System.out.println(“Volume = “
14. + sandal.box.getVolume());
15. }
16.}
Here is a breakdown of main :
1. A Shoe object is instantiated on line 12, invoking the constructor on line 6.
2. A new Box is instantiated on line 8 with dimensions 6 by 10 by 4, which has a volume
of 240.
3. The volume is printed out on line 14.
Therefore, the output of this program is
Volume = 240
Importing a Nested Class
Because a static nested class is a static member of a class, it can be imported using a
static import. For example, suppose Shipment is in the com.sybex.demos package. Then
we can import the Box class using the following static import:
import static com.sybex.demos.Shipment.Box;
You might be surprised to fi nd out that you can also import the Box class using a regular
import statement. For example, the following Cereal class is valid and compiles
successfully:
import com.sybex.demos.Shipment.Box;
public class Cereal {
Box box;
}
Being able to use an import statement like the one in Cereal is an example of how
declaring a static nested class is like creating a namespace.
Search WWH ::




Custom Search