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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With