这个Java泛型范例做了什么以及它叫什么? [英] What does this Java generics paradigm do and what is it called?

查看:108
本文介绍了这个Java泛型范例做了什么以及它叫什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

public
abstract
class A< E extends A< E>>实现可比较的< E> {

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

public
class B延伸A B< B> {
// etc
}

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


这里我使用Comparable只是为了说明泛型参数E的可能用法。这种泛型/继承的用法是否有名字?它的用途是什么?



我的印象是这允许抽象类提供方法的一个公共实现(比如compareTo),而不必在子类。但是,在本例中,与继承方法不同,它将限制子类在相同子类的其他实例上调用compareTo,而不是任何A子类。这听起来是对的吗?

无论如何,只是好奇的是,如果有任何专家在那里看到过,并知道它做了什么。



谢谢!

解决方案

在C ++中,它被称为奇怪的循环模板模式(CRTP)。我不知道它是否在Java中有不同的名称(或者即使它有一个名称),但它可能用于类似的目的。


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!

解决方案

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.

这篇关于这个Java泛型范例做了什么以及它叫什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆