1
votes

There is a generic interface:

public interface IMyQueue<T> {
  //...
}

and there is a generic class implementing it:

public class MyQueueImp<T> implements IMyQueue<T> {
  //...
}

I want the implementation to have a factory method: a public static method getInstance that instantiate an object for that generic class.

public class MyQueueImp<T> implements IMyQueue<T> {
  public static IMyQueue getInstance() {
     ///....
  }
}

So I can call it like this:

IMyQueue<Integer> queue = MyQueueImpl.getInstance();

The problem is within this static methods there is not access to generic T:

MyPriorityQueueImpl.this' cannot be referenced from a static context

I'm wondering how should I do this?

1

1 Answers

2
votes

Your factory method is static, so it knows nothing of the actual argument for T. You would have to declare it on the method itself:

public static <U> IMyQueue<U> getInstance() {
   return new MyQueueImp<U>(); //or whatever instantiation you have
}

Side note: it's a bit strange to have an IMyQueue factory in one specific implementation of IMyQueue. Perhaps a better place to put this factory method is a separate class, or you could even put it in IMyQueue itself.