1

If I have a class:

class Foo<T> {}

Is it legal / does it make sense to do this?

class Foo<T, R extends Foo<T, R>> {}

For context, I am trying to implement this pattern for a Builder that already has one generic parameter.

Aidenhjj
  • 1,249
  • 1
  • 14
  • 27

2 Answers2

1

Yes, it is legal to have recursive generic types. The canonical example is

package java.lang;
public abstract class Enum<E extends Enum<E>>

from the JRE.

memo
  • 1,868
  • 11
  • 19
  • My question is, what if the class has a generic parameter that it's not recursive on? – Aidenhjj Nov 07 '18 at 13:03
  • It shouldn't matter. And your code compiles just fine. Now if it makes sense, that I can't tell right away – memo Nov 07 '18 at 13:04
1

I`m not sure, if I'm properly getting your additional question in your comment. But let's try to explain.

The class with what you call "recursive parameter" is definitely legal and it makes sense.

It's used in "extendable" builders. Let's see following example:

public interface BaseBuilder<T, B extends BaseBuilder<T,B> {
    B add(String field, String value);

    default B person(String firstName, String lastName) {
        // This chaining is only possible thanks to that recursive parameter
        return add("firstName", firstName).add("lastName", lastName);
    }

    T build();

    default T buildPerson(String firstName, String lastName) {
        return person(firstName, lastName).build();
    }
}

You re-use this e.g. like this:

 public interface MyBuilder<T> extends BaseBuilder<T, MyBuilder<T> {}
Ondřej Fischer
  • 411
  • 1
  • 7
  • 16