Loay
Loay

Reputation: 601

is it possible for a parameterized class to extend itself in java?

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.

Upvotes: 2

Views: 801

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42441

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

Upvotes: 4

Related Questions