0

Thank you all for reading, i'm trying to understand Generics, and i got this excersice where i create a singleton with a generic parameter.

public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null; } 

But i got this error: Cannot make a static reference to the non-static type T

What can i use as a workaround? Or better yet, what causes the error?

1
  • It doesn't make sense to have a generic singleton anyway. You can only have one, so what's the point of having different ones for different base types? Commented Apr 25, 2017 at 15:05

1 Answer 1

0

Look at newaccts answer to this post:

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.