递归类型界限的使用 [英] Uses of recursive type bounds
问题描述
A friend of mine found this tidbit in the Java API (https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html),
Class Enum<E extends Enum<E>>
并阅读以下文章 https://docs.oracle. com/javase/tutorial/java/generics/genTypes.html 我可以理解上述行在语法上的含义,但是从给出的示例中,我无法找出Enum类以外的用例(查看源代码)
and by reading the following article https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html I could understand what the aforementioned line entailed syntactically but from the examples given I could not figure out a use case for this beyond the Enum class (reviewed the source).
我想详细了解上述可能提出解决方案的可能问题.
I'd like to learn more about possible problems where the above may present a solution.
推荐答案
例如,允许子类使用自己的类型很有用
It's for example useful to to allow subclasses to use their own type
想象一个像
class Node {
Node next;
}
如果您扩展该类,则会陷入Node
.
if you extend that class, you're stuck with Node
.
class SpecialNode extends Node {
void foo() {
// euwww
SpecialNode nextNode = (SpecialNode) this.next;
}
}
您也不能像这样定义它
class Node<T> {
T next;
}
因为这将允许T
使用任何内容.您确实想要一个extends Node
的T
,或者您不能在不强制转换的情况下将Node
中的T用作Node
.不过,它适用于子班.
because that would allow anything for T
. You really want a T
that extends Node
or you can no longer use T as Node
from within Node
without casting. It would work for child classes though.
通过使用递归边界,如
class Node<T extends Node<T>> {
T next;
}
您将T限制为您自己或您自己的子类,然后您就可以这样做
You limit T to yourself or subclasses of yourself which then allows you to do
class SpecialNode extends Node<SpecialNode> {
void foo() {
SpecialNode nextNode = this.next; // type-safe!
}
}
这样,父类和子类都可以完全抽象安全地访问其抽象级别上的所有内容.
That way both parent and child class can access everything on their abstraction level fully typesafe.
这篇关于递归类型界限的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!