I use the builder pattern (as explained in Joshua Bloch Effective Java) for several things, and it was particularly annoying to repeat:
public class Foo {
private String name;
private int age;
public static class Builder implements IBuilder {
private String name;
private int age;
Builder name(String value) {
name = value;
return this;
}
Builder age(int value) {
age = value;
return this;
}
Foo build() {
return new Foo(this);
}
}
private Foo(Builder builder) {
name = builder.name;
age = builder.age;
}
}
It is small but annoying. I have to declare a variable in each class. I tried to create a class with the fields and extend this class, but I got an error: {variable_name} has private access in {class_name}.
Is there a way to do this without making the variables publicly available?
source
share