1

I came across this definition of a class that was written by someone else:

BaseClass<E extends BaseClass<E>>

All of the class's methods are then defined this way:

public<E> E setX(...) {
   // do stuff
   return this;
} 

And an object of class BaseClass is used like this:

base.setX(..).setY(..).setZ()..

And it got me wondering as to how it works,why does it even compile,why it's used this way and if it's good practice to declare a class to extend itself.

Any help would be much appreciated.

Loay
  • 483
  • 3
  • 18
  • "All of the class's methods are then defined this way: public E setX(...) { // do stuff return this; } " I don't think that would compile as a method of `BaseClass`. First, the way you wrote it, `E` is generic on the method, unrelated to the class's `E`, and can be anything, so there is no way to guarantee that `BaseClass` is a subtype of `E2`. Even if you remove the `` from the method so it uses the class's `E`, it is still not guaranteed that `BaseClass` is a subtype of `E`. – newacct Jan 12 '20 at 02:40

1 Answers1

3

The word "extends" here is used to specify a boundary on the parametrization (E) and not for self-inheritance. Self inheritance in Java is prohibited, period.

Essentially it says:

BaseClass is parameterized with E. But E can not be of any type (like String, Integer, etc.) Instead E must be of type of something that extends BaseClass.

I saw this technique to create builders hierarchy which also look to be your case as well.

You might be interested in reading this thread

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97