java - 当方法名与类名相同时如何实例化嵌套类?

标签 java class instance builder

先写代码。

class A
{
    private A(){}
    public static A.Builder Builder()
    {
        /**
         * ERROR:
         * No enclosing instance of type A is accessible. 
         * Must qualify the allocation with an enclosing instance of type A 
         * (e.g. x.new A() where x is an instance of A).
         */
        return new A.Builder();
        // Error too
        //return new Builder();
    }

    public class Builder
    {
        private Builder()
        {}
    }
}

问:如何实例化构建器但不更改静态构建器和嵌套类名称?

编辑

如果类是静态的,如何保存每个构建器的日期?如何链接构建过程?

public static class Builder
{
    private Builder()
    {}

    public Builder add(int a)
    {
        return this;// how to chain the build process ?
    }
    public Builder add(float a);
    public List<Double> Build();
}

好的,我应该首先谷歌 Java 构建器模式。 Here就是一个例子。

最佳答案

规则:如果内部类在封闭类之外使用,则它必须是静态的。

public static class Builder
{
    private Builder()
    {

    }
}

这是设计使然。

关于java - 当方法名与类名相同时如何实例化嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22196185/

相关文章:

vb.net - 对象的深拷贝

c++ - 一个文件无法识别 C++ 中其他文件的类

javascript - 从数组的副本中删除一个项目而不从原始数组中删除它

python - 在Python中,如何检查我的类的实例是否存在?

java - 像 a[1][1][1][1]....[1] 这样的 Java 支持多少维数组?

C++ 类前向声明​​的缺点?

Java的可比接口(interface): Handling null arguments to compareTo()

haskell - 为什么在创建类型类实例时不能下划线(忽略)类型变量?

java - Eclipse RCP Job cancel() 方法始终返回 false

java - 如何将图像保存到用户的手机上?然后加载它?