[英]Java: Inheriting a generic class and setting its type
I have a generic Link class (to implement a linked list), as seen below: 我有一个通用的Link类(用于实现链接列表),如下所示:
class Link<T> {
protected T next;
public T getNext() { return next; }
public void setNext(T newnext) { next = newnext; }
} // end class Link
Now, I want another class called Card to inherit from this. 现在,我希望另一个名为Card的类从中继承。
class Card extends Link {
...
}
However, I want it to return a Card object for getNext(). 但是,我希望它为getNext()返回Card对象。 How do I do this? 我该怎么做呢?
Originally, the Link class was not generic, but then I had to perform a cast on getNext() every time I wanted to use it. 最初,Link类不是通用的,但是每次我想使用它时,都必须在getNext()上执行强制类型转换。 I was having a seemingly related null pointer issue, so I wanted to clear this out of the way. 我遇到了一个看似相关的空指针问题,所以我想清除此问题。
You can specify that the generic parameter type for Link
to be Card
in Card
: 您可以将“ Link
的通用参数类型指定为Card
in Card
:
class Card extends Link<Card>
This assigns Card
to the generic type parameter T
from Link
. 这会将Card
从Link
分配给通用类型参数T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.