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 ;)
Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
So methods of generic or nongeneric classes can use generic types as argument and return types as well. Here are examples of those usages: // Not generic methods class GenericClass < T > { // method using generic class parameter type public void T cache ( T entry ) { ... } }
We can use generics while defining our builders to tell Java that return type of methods is not the builder's class but rather the subclass of the builder, hence recursive generic definition.
you could try:
class A<T> { }
class B<T extends A<? super T>> extends A<T> { }
class C extends B<C> { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With