views:

127

answers:

2

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!

+5  A: 

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.

Etienne de Martel
That wiki page has essentially the explanation I was looking for, thanks! I found the note about compile-time "static" polymorphism rather interesting.
Tom
There's a nice Java-oriented discussion of it here: http://madbean.com/2004/mb2004-3/ Look for the heading "More tricks with type parameters"
Alan Moore
+1  A: 

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).

ILMTitan