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?

Rohr Facu
  • 607
  • 1
  • 12
  • 29
  • 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? – Lew Bloch Apr 25 '17 at 15:05

1 Answers1

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.

Community
  • 1
  • 1
ITiger
  • 1,056
  • 3
  • 11
  • 24