Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Java generics paradigm do and what is it called?

I'm looking at some Java classes that have the following form:


public 
abstract
class A <E extends A<E>> implements Comparable <E> {

   public final int compareTo( E other ) {
      //  etc
   }   
}

public 
class B extends A <B> {
   // etc
}

public 
class C extends A <C> {
   // etc
}


My usage of "Comparable" here is just to illustrate a possible use of the generic parameter "E". Does this usage of generics/inheritance have a name? What is it used for?

My impression is that this allows the abstract class to provide a common implementation of a method (such as compareTo) without having to provide it in the subclasses. However, in this example, unlike an inherited method it would restrict subclasses to invoking compareTo on other instances of the same subclass, rather than any "A" subclass. Does this sound right?

Anyway, just curious if any gurus out there have seen this before and know what it does.

Thanks!

like image 228
Tom Avatar asked Mar 04 '10 21:03

Tom


People also ask

What does generics do in Java?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.

What is the generic class type called?

Generic Classes These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

What is generic programming and why is it needed?

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.

What does generic type mean in Java?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


2 Answers

In C++, it's known as the Curiously Recurring Template Pattern (CRTP). I don't know if it has a different name in Java (or even if it has a name), but it probably serve similar purposes.

like image 65
Etienne de Martel Avatar answered Oct 03 '22 10:10

Etienne de Martel


I believe it is usually just called a Recursive Generic Type. As Tom Hawtin points out, you probably want class A<E extends A<E>>. The most prominent use of this pattern is java.lang.Enum (which you probably knew considering you chose Comparable<E> as your interface).

like image 40
ILMTitan Avatar answered Oct 03 '22 08:10

ILMTitan