Can one create an extensible class hierarchy in java whose methods are fluent and can be invoked in any order? (YES! see answer below), even for existing classes wh
If source code is accessible, by extending what Alan wrote, I would add supplementary classes to hide generics while allowing inheritance and very compact syntax. BaseA and BaseB do the hierarchy while A and B do hide the generics.
BaseA
+- A
+- BaseB
+- B
public class BaseA> {
private String a = null;
protected BaseA() {
}
@SuppressWarnings("unchecked")
public S setA(String a) {
this.a = a;
return (S) this;
}
}
public class A extends BaseA {
public static A factoryA() {
return new A();
}
}
public class BaseB> extends BaseA {
private String b = null;
protected BaseB() {
}
@SuppressWarnings("unchecked")
public S setB(String b) {
this.b = b;
return (S) this;
}
}
public class B extends BaseB {
public static B factoryB() {
return new B();
}
}
public class Main {
public static void main(String[] args) {
B.factoryB().setA("").setB("").setB("").setA("").setA("");
}
}