Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics Type paramenter depends on itself

Tags:

java

generics

I came across with following:

I understand this :

In a class's type parameter section, a type variable T directly depends on a type variable S if S is the bound of T, while T depends on S if either T directly depends on S or T directly depends on a type variable U that depends on S (using this definition recursively).

But

It is a compile-time error if a type variable in a class's type parameter section depends on itself.

what does it mean ? Reference

like image 388
optional Avatar asked Jan 24 '17 11:01

optional


2 Answers

What the statement means is that a type parameter variable cannot depend on itself. The following code is not allowed :

class Generic<T extends T> {

}

Here T is a type-parameter variable and it cannot depend on itself (directly or inderictly). On the other hand, the following code is allowed :

public class GenericRecursive<T extends GenericRecursive<T>> {

}
like image 73
Chetan Kinger Avatar answered Oct 18 '22 17:10

Chetan Kinger


It is a compile-time error if a type variable in a class's type parameter section depends on itself.

The parameter cannot derives from itself.

For example it is not legal :

class YourClass<S extends S> { 
}

But you probably will not use this as it makes no really sense.

You could do that for example :

class YourClass<T extends S, S extends T> { 
}

And it will not compile too because T depends on S that depends on itself (cycle)

like image 32
davidxxx Avatar answered Oct 18 '22 18:10

davidxxx