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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With