简体   繁体   中英

Java: Inheriting a generic class and setting its type

I have a generic Link class (to implement a linked list), as seen below:

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.

class Card extends Link {
...
}

However, I want it to return a Card object for getNext(). 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. 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 :

class Card extends Link<Card>

This assigns Card to the generic type parameter T from Link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM