Generics in Java
Asked Answered
D

1

7

I would like to understand the following type of syntax.

Example:

public interface A < T extends A < T> > {

}

What is the logic of this interface ?

Dikdik answered 18/11, 2011 at 18:59 Comment(4)
strongly related: https://mcmap.net/q/136053/-java-enum-definitionSholeen
also related: https://mcmap.net/q/1021236/-recursive-generic-usageSholeen
related to possible uses: #7959835Sholeen
possible duplicate of Generics in JavaCelin
S
14

This would be used as follows:

class X implements A<X> { /* ... */ }

In other words, you are forced to make the parameter of A the class X itself, and something like class X implements A<Unrelated> is forbidden.

This construction gives the interface access to X through the generic parameter, and the type restriction makes sure that it doesn't get abused. For instance, T can now be assumed to expose all methods that A does.

Note that this construction is formally somewhat similar to the curiously recurring template pattern in C++ (although it is technically quite different). In both languages it allows the "base class" to reason about its ultimate derived usage.

Shererd answered 18/11, 2011 at 19:4 Comment(1)
This is a great explanation. I'm wondering though, what are some applications of this other than the Enum usage already suggested? A linked list maybe?Electrodeposit

© 2022 - 2024 — McMap. All rights reserved.