static内部类

王朝other·作者佚名  2008-05-19
宽屏版  字体: |||超大  

为正确理解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”命令)。可将这个类用于测试,但不需在自己的最终发行版本中包含它。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有