You can’t access a non-static outer-class object from an object
of a nested class.
//: c08:Parcel10.java
// Nested classes (static inner classes).
public class Parcel10 {
private static class ParcelContents implements Contents {
private int i = 11;
public int value() { return i; }
}
protected static class ParcelDestination
implements Destination {
private String label;
private ParcelDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
// Nested classes can contain other static elements:
public static void f() {}
static int x = 10;
static class AnotherLevel {
public static void f() {}
static int x = 10;
}
}
public static Destination dest(String s) {
return new ParcelDestination(s);
}
public static Contents cont() {
return new ParcelContents();
}
public static void main(String[] args) {
Contents c = cont();
Destination d = dest("Tanzania");
}
} ///:~
In main( ), no object of Parcel10 is necessary; instead, you use the normal syntax for selecting a static member to call the methods that return references to Contents and Destination.
As you will see shortly, in an ordinary (non-static) inner class, the link to the outer class object is achieved with a special this reference. A nested class does not have this special this reference, which makes it analogous to a static method.
Normally, you can’t put any code inside an interface, but a nested class can be part of an interface. Since the class is static, it doesn’t violate the rules for interfaces—the nested class is only placed inside the namespace of the interface:
//: c08:IInterface.java
// Nested classes inside interfaces.
public interface IInterface {
static class Inner {
int i, j, k;
public Inner() {}
void f() {}
}
} ///:~
Earlier in this book I suggested putting a main( ) in every class to act as a test bed for that class. One drawback to this is the amount of extra compiled code you must carry around. If this is a problem, you can use a nested class to hold your test code:
//: c08:TestBed.java
// Putting test code in a nested class.
public class TestBed {
public TestBed() {}
public void f() { System.out.println("f()"); }
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
} ///:~
This generates a separate class called TestBed$Tester (to run the program, you say java TestBed$Tester). You can use this class for testing, but you don’t need to include it in your shipping product; you can simply delete TestBed$Tester.class before packaging things up.