创建静态嵌套类的实例

时间:2013-11-10 22:35:47

标签: java nested-class

我相信每当你创建一个静态嵌套类的实例时,它应该是这样的:

Outerclass.StaticNestedClass myObject = new Outerclass.StaticNestedClass();

下面的代码(我省略了一些我认为不相关的代码)不使用封闭的类名。 GeneratedData是ObjectBuilder类的静态嵌套类。我为什么不看:

ObjectBuilder.GeneratedData = ObjectBuilder.createMallet()

相反,有:

GeneratedData generatedData = ObjectBuilder.createMallet();

这是java文件......

public class Mallet {
public Mallet(float radius, float height, int numPointsAroundMallet) {

    GeneratedData generatedData = ObjectBuilder.createMallet(new Point(0f,
        0f, 0f), radius, height, numPointsAroundMallet);

    // lots of code omitted

}
}    

这里是定义静态嵌套类的类。如您所见,createMallet()方法创建一个GeneratedData类型的对象,上面的Mallet类使用该方法而不是构造函数。

class ObjectBuilder {

static interface DrawCommand {
    void draw();
}

static class GeneratedData {
    final float[] vertexData;
    final List<DrawCommand> drawList;

    GeneratedData(float[] vertexData, List<DrawCommand> drawList) {
        this.vertexData = vertexData;
        this.drawList = drawList;
    }
}

static GeneratedData createMallet(
    // lots of code omitted
    return builder.build();
}    

private final float[] vertexData;

private ObjectBuilder(int sizeInVertices) {
    vertexData = new float[sizeInVertices * FLOATS_PER_VERTEX];
}

private GeneratedData build() {
    return new GeneratedData(vertexData, drawList);
}
}

1 个答案:

答案 0 :(得分:2)

因为您可以import xyz.ObjectBuilder.GeneratedData之后在课程中使用GeneratedData