I’ve read that you cannot declare static variables/methods inside a generic class and I really have no idea how to solve my problem or work around it so I ask for your guidance.
What I want is a generic “index” that all of my core classes will extend.
I’m creating a game-engine and an example is that I will have different gamestates who all extends State who in turn extends Nexus<State>. The reason I want the static head and tail is so that I can keep a linked list of all gamestates since they’re all added to that list upon creation.
Another example is that I will have different gameobjects who all extends GameObject who in turn extends Nexus<GameObject>.
This is the index called Nexus:
public abstract class Nexus<T>
{
private static T head = null;
private static T tail = null;
private T next = null;
private static int num = 0;
protected Nexus() { this.Add( (T)this ); }
public T Add( T obj )
{
((Nexus)obj).next = null;
if( num++ == 0 ) head = tail = obj;
else tail = ( tail.next = obj );
return obj;
}
}
If anyone got another solution or a workaround I’m all ears!
Try this approach: Define a
protected abstractmethod that subclasses implement to return astaticobject for their class.There may be some logic issues etc, but the basics of the answer are here (ie this compiles):
EDITED: Now delegating to HeadAndTail