Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring static generic variables in a generic class

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!

like image 945
Tanax Avatar asked Jul 05 '11 00:07

Tanax


1 Answers

Java generics are quite different than C# generics. There is type erasure, so you can't say something like Nexus<T>.aStaticPublicField (as in C#). You can only say Nexus.aStaticPublicField. There is no way to know what the generic type is (as you don't have an instance), so therefore you can't have a static field of type T.

like image 114
Petar Ivanov Avatar answered Oct 13 '22 19:10

Petar Ivanov