先写代码。
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/