为正确理解static在应用于内部类时的含义,必须记住内部类的对象默认持有创建它的那个封装类的一个对象的句柄。然而,假如我们说一个内部类是static的,这种说法却是不成立的。static内部类意味着:
(1) 为创建一个static内部类的对象,我们不需要一个外部类对象。
(2) 不能从static内部类的一个对象中访问一个外部类对象。
但在存在一些限制:由于static成员只能位于一个类的外部级别,所以内部类不可拥有static数据或static内部类。
倘若为了创建内部类的对象而不需要创建外部类的一个对象,那么可将所有东西都设为static。为了能正常工作,同时也必须将内部类设为static。如下所示:
//: parcel10.java
// static inner classes
package c07.parcel10;
abstract class contents {
abstract public int value();
}
interface destination {
string readlabel();
}
public class parcel10 {
private static class pcontents
extends contents {
private int i = 11;
public int value() { return i; }
}
protected static class pdestination
implements destination {
private string label;
private pdestination(string whereto) {
label = whereto;
}
public string readlabel() { return label; }
}
public static destination dest(string s) {
return new pdestination(s);
}
public static contents cont() {
return new pcontents();
}
public static void main(string[] args) {
contents c = cont();
destination d = dest("tanzania");
}
} ///:~
在main()中,我们不需要parcel10的对象;相反,我们用常规的语法来选择一个static成员,以便调用将句柄返回contents和destination的方法。
通常,我们不在一个接口里设置任何代码,但static内部类可以成为接口的一部分。由于类是“静态”的,所以它不会违反接口的规则――static内部类只位于接口的命名空间内部:
//: iinterface.java
// static inner classes inside interfaces
interface iinterface {
static class inner {
int i, j, k;
public inner() {}
void f() {}
}
} ///:~
在本书早些时候,我建议大家在每个类里都设置一个main(),将其作为那个类的测试床使用。这样做的一个缺点就是额外代码的数量太多。若不愿如此,可考虑用一个static内部类容纳自己的测试代码。如下所示:
//: testbed.java
// putting test code in a static inner class
class testbed {
testbed() {}
void f() { system.out.println("f()"); }
public static class tester {
public static void main(string[] args) {
testbed t = new testbed();
t.f();
}
}
} ///:~
这样便生成一个独立的、名为testbed$tester的类(为运行程序,请使用“java testbed$tester”命令)。可将这个类用于测试,但不需在自己的最终发行版本中包含它。
闽公网安备 35060202000074号