Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 382
Chris Chambers Avatar asked Dec 20 '22 06:12

Chris Chambers


1 Answers

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.

like image 128
rgettman Avatar answered Jan 05 '23 04:01

rgettman