开发者

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 compa开发者_如何学PythonreTo 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!


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.


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


It does not have a name and it is generally not useful. Probably the person who wrote it did not realize that they could write it like this instead:

class A<E> implements Comparable<E>

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.

Not any more than class A<E>

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?

No, that's incorrect. It restrict it to invoking compareTo on E, whatever E is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜