Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in Java

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 ?

like image 298
Lior Avatar asked Nov 18 '11 18:11

Lior


People also ask

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Why generics are used in Java?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

How do you explain generics?

Genetics is the scientific study of genes and heredity—of how certain qualities or traits are passed from parents to offspring as a result of changes in DNA sequence. A gene is a segment of DNA that contains instructions for building one or more molecules that help the body work.


1 Answers

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.

like image 111
Kerrek SB Avatar answered Sep 23 '22 13:09

Kerrek SB