It’s probably a bit difficult to describe. However, I’ll try it 😉
Following the fluent style, it is common that a method of a class returns the class instance itself (this).
public class A {
public A doSomething() {
// do something here
return this;
}
}
When extending such a fluent style class one could do this rather easy in the first inheritance step via a generic type and casting the return type to this generic type in the super class.
public class A<T extends A<T>> {
public T doSomething() {
// do something here
return (T) this;
}
}
public class B extends A<B> {
// an extended class of class A
}
However, when doing another inheritance step on this extended class, I’m running into trouble when trying to define the generic return type of the methods (in the upper classes) and the class description itself, e.g., a method in the super-super class would not return the type of the extend class but rather then the type of the super-class. However, my intention was that these fluent style methods should always return the type of the current class (and not is upper classes).
So is it possible to define a solution by utilising generics?
PS: I know, a simple workaround might be override all these method in the extended class and cast them to the current type. However, I’m interested in a more elegant solution 😉
you could try: