Take the 2-minute tour ×

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!

share|improve this question
10 seconds with the compiler would have told you that you can do this. Your source is wrong. –  EJP Jul 5 '11 at 0:38
Given the name of your static fields, it is almost certainly the case that you shouldn't be using static fields here. That would be true with or without your generics. But where did you read that one should always avoid static members in generic classes? Never heard that myself, and I strongly disagree. –  Kirk Woll Jul 5 '11 at 0:39
That is weird, I got this: Exception in thread "main" java.lang.ExceptionInInitializerError at Game.main(Game.java:29) Caused by: java.lang.RuntimeException: Uncompilable source code - non-static type variable T cannot be referenced from a static context at Nexus.<clinit>(Nexus.java:13) ... 1 more Java Result: 1 –  Tanax Jul 5 '11 at 0:47
@Kirk A quick google search of "non-static type variable cannot be referenced from a static context" gave me tons of results that all said what I wrote, a lot coming from this site :/ –  Tanax Jul 5 '11 at 0:51
@Tanax No. None of them said you can't have static variables in a generic class, and neither did the compiler, or that compiler error message, or the exception. –  EJP Jul 5 '11 at 0:56
show 6 more comments

4 Answers

up vote 3 down vote accepted

Try this approach: Define a protected abstract method that subclasses implement to return a static object 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

/** <T> A subclass of Nexus */
abstract class Nexus<T extends Nexus<T>> { // This syntax lets you confine T to a subclass of Nexus
    private T next;

    protected Nexus() {
        this.add((T) this);

    public T add(T obj) {
        // Delegate to HeadAndTail
        return getHeadAndTail().add(obj);

    /** @return a static for the class */
    protected abstract HeadAndTail<T> getHeadAndTail();

/** Bundled into one Object for simplicity of API */
class HeadAndTail<T extends Nexus<T>> {
    T head = null;
    T tail = null;
    int num = 0;

    public T add(T obj) {
        obj.next = null;
        if (num++ == 0)
            head = tail = obj;
            tail = tail.next = obj;

        return obj;

class ConcreteNexus extends Nexus<ConcreteNexus> {
    // This is the static object all instances will return from the method
    private static HeadAndTail<ConcreteNexus> headAndTail = new HeadAndTail<ConcreteNexus>();

    protected HeadAndTail<ConcreteNexus> getHeadAndTail() {
        return headAndTail; // return the static
share|improve this answer
That should work, but... reuse the return reference from getHeadAndTail instead of calling in multiple times. –  Ben Voigt Jul 5 '11 at 1:26
That looks awesome! I will try implement it and see if it works :D –  Tanax Jul 5 '11 at 1:34
It is problematic to have the constructor of an abstract class call a virtual method. –  bobbymcr Jul 5 '11 at 1:36
This code worked great when I only had one type(I tested it with 2 different gamestate-classes who both extended state who extended Nexus<State>).But when I added a gameobject who extends GameObject that extended Nexus<GameObject> I got an exception: Exception in thread "main" java.lang.NullPointerException at Nexus.Add(Nexus.java:35) at Nexus.<init>(Nexus.java:16) at GameObject.<init>(GameObject.java:17) at SpaceShip.<init>(Game.java:47) at Game.main(Game.java:67) I really cannot understand why it gives me this Nexus, 35 is: GetHeadAndTail().tail = ( GetHeadAndTail().tail.next = obj ); –  Tanax Jul 5 '11 at 2:12
Oh, I know! Num is static and shared between all Nexus classes, thus head and tail will never be initialized for that typename since num is not 0. –  Tanax Jul 5 '11 at 2:16
show 3 more comments

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.

share|improve this answer
Yes, that is exactly what I found out on all the other questions regarding this on this site. Do you know another way of accomplishing what I need or a workaround? –  Tanax Jul 5 '11 at 0:56
@Tanax: You could keep a dictionary of (head,tail) pairs, keyed by type. –  Ben Voigt Jul 5 '11 at 0:59
I will look into it, thanks! –  Tanax Jul 5 '11 at 1:02
add comment

according to http://download.oracle.com/javase/tutorial/java/IandI/abstract.html


But I haven't yet tested this myself

share|improve this answer
I'm pretty sure that tutorial predates generics. –  Ben Voigt Jul 5 '11 at 0:47
couldn't you just put AbstractClass.staticMethod<type>() –  Tom Busby Jul 5 '11 at 0:48
Hello Tom! I don't think it's the abstract that is the fault here, but the generics ( <T> ). –  Tanax Jul 5 '11 at 0:52
thing is, looking at your code, I don't get why head and tail would be static. What you appear to be implementing is a Singly-linked list, in which case head and tail shouldn't be static or you'll only ever be able to have one instance of the class, otherwise any new instance will overwrite the head and tail for all the other instances –  Tom Busby Jul 5 '11 at 0:56
((Nexus)obj).next = null; this is a very strange line too, are you sure you want to convert the object passed in into a Nexus object? –  Tom Busby Jul 5 '11 at 0:58
show 1 more comment

A set of static fields is not a very good way to achieve this. I don't quite understand your requirements but it seems like a better way would be to change the signature of the constructor for this class to pass in the global index object.

That is, instead of this:


... you could do this instead:

protected Nexus(GameStateIndex<T> index) { index.Add(this); }

This properly separates the responsibilities of tracking the game state and keeping track of the index of all game states. (See the "Single responsibility principle".) It also makes it explicitly clear that creation of a state object comes with a dependency on indexing that state properly.

share|improve this answer
Sorry, maybe I did a poor job at explaining what I wanted in the original post but what I want to be able to do is to create .. for instance StateOne who extends State(which contains various methods). State in turn, extends Nexus<State> so what I create an instance of StateOne it will automatically get added to the internal static linked list in Nexus<State>. I also want to be able to create a SpaceShip who extends GameObject(which also contains various methods) who in turn extends Nexus<GameObject> so when I create an instance of SpaceShip it will get added to the list in Nexus<GameObject> –  Tanax Jul 5 '11 at 1:10
add comment

Your Answer


