Java: inherit a common class and set its type

I have a generic Link class (for implementing a linked list), as shown 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 to do it?

The Link class was not originally generic, but then I had to cast getNext () every time I wanted to use it. I had a seemingly problem with a null pointer, so I wanted to fix this.

+4
source share
1 answer

You can specify that the general parameter type for Link should be Card in Card :

 class Card extends Link<Card> 

This assigns Card parameter of general type T from Link .

+11
source

All Articles