Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self-referential methods with generic return type for multiple inherited classes

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 ;)

like image 414
zazi Avatar asked Jun 21 '12 17:06

zazi


People also ask

Can generics be used with inheritance in several ways what are they?

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.

Can generic classes be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

Can Java return type be generic?

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 ) { ... } }

What is recursive generics in Java?

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.


1 Answers

you could try:

class A<T> { }

class B<T extends A<? super T>> extends A<T> { }

class C extends B<C> { }
like image 102
haed Avatar answered Nov 14 '22 02:11

haed