I'm having an issue with a self-bounding generic type which has a self-bounding generic subtype.
I'm trying to implement some kind of builder pattern and i'd like to have my statements more or less like in the main method.
Can anyone help me out in finding a better why to declare the generics so I no longer need the cast and I don't get compilation errors in the statements. Or can anyone explain in clear text why this can't work?
import java.util.Date;
public class SelfBoundingGenericTypeTest {
public static void main(String[] args) {
ConcreteType type = new ConcreteType().pageSize(1).id(12);
SubType type2 = (SubType) new SubType().id(10).pageSize(0); // Why do i need the cast?
SubType type3 = new SubType().pageSize(0).id(10); // Compile error
}
}
abstract class SuperType<E extends SuperType<E>> {
private int _pageSize = Integer.MIN_VALUE;
private int _startIndex = Integer.MIN_VALUE;
@SuppressWarnings("unchecked")
public E pageSize(int value) {
this._pageSize = value;
return (E) this;
}
@SuppressWarnings("unchecked")
public E startIndex(int value) {
this._startIndex = value;
return (E) this;
}
public int getPageSize() {
return _pageSize;
}
public int getStartIndex() {
return _startIndex;
}
}
class SubType<E extends SubType<E>> extends SuperType<E> {
private long _id = Long.MIN_VALUE;
@SuppressWarnings("unchecked")
public E id(long value) {
this._id = value;
return (E) this;
}
public long getId() {
return _id;
}
}
class ConcreteType extends SubType<ConcreteType> {
private Date _startDate;
public Date getStartDate() {
return _startDate;
}
public ConcreteType startDate(Date value) {
this._startDate = value;
return this;
}
}