For the rest I'll let the code talk about the issue & a possible solution in more detail:
package com.arjun.misc;
/**
* "Setter chaining". The issue is that it returns the object of the
* type of the class in which the setter is.
* For Inheritance concepts this means if A<--B; then B.a()
* will return A not B (exclude overriding).
* This hardly helps chaining. Using generics to solve the problem
*
* @author Arjun Dhar | www.neurosys.biz
* */
public class GenericChainingSetters {
private static class A<T extends A> {
T setA(String something) {
return (T)this;
}
}
private static class B<T extends B> extends A<T> {
T setB(String something) {
return (T)this;
}
}
private static class C<T extends C> extends B<T> {
T setC(String something) {
return (T)this;
}
}
public static void main(String[] args) {
//WORKS
B<B> b = new B();
b.setA("abc").setB("abc again?!");
//WORKS
C<C> c = new C();
c.setA("abc").setB("abc again?!").setC("Hurray!");
}
}
Only thing is that as with Generics (erasure),
one cant (can but should not logically) do something stupid like:
B<C> b = new B();
Thoughts & suggestions welcome
thanks
-Arjun
Click here to see better way using Java 8