I have an object hierarchy that increases in complexity as the inheritance tree deepens. None of these are abstract, hence, all of their instances serve a, more or less soph
This form seems to nearly work. It is not very tidy but it looks like it avoids your issues:
class Rabbit> {
String name;
public Rabbit(Builder builder) {
this.name = builder.colour;
}
public static class Builder> {
protected String colour;
public B colour(String colour) {
this.colour = colour;
return (B)this;
}
public Rabbit build () {
return new Rabbit<>(this);
}
}
}
class Lop> extends Rabbit {
float earLength;
public Lop(Builder builder) {
super(builder);
this.earLength = builder.earLength;
}
public static class Builder> extends Rabbit.Builder {
protected float earLength;
public B earLength(float earLength) {
this.earLength = earLength;
return (B)this;
}
@Override
public Lop build () {
return new Lop<>(this);
}
}
}
public class Test {
public void test() {
Rabbit rabbit = new Rabbit.Builder<>().colour("White").build();
Lop lop1 = new Lop.Builder<>().earLength(1.4F).colour("Brown").build();
Lop lop2 = new Lop.Builder<>().colour("Brown").earLength(1.4F).build();
//Lop.Builder builder = new Lop.Builder<>();
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
Although I have successfully built Rabbit
and Lop
(in both forms) I cannot at this stage work out how to actually instantiate one of the Builder
objects with it's full type.
The essence of this method relies on the cast to (B)
in the Builder
methods. This allow you to define the type of object and the type of the Builder
and retain that within the object while it is constructed.
If anyone could work out the correct syntax for this (which is wrong) I would appreciate it.
Lop.Builder builder = new Lop.Builder<>();