4

Consider the code:

public class A<T extends X> {
  public static interface Delegate {
    void doMagic(T t); // why can't I access "T" here?
  } 

  public A(Delegate delegate) { ... }
}
...
public class TheDelegate implements A<Y> { ... }
...
A<Y> a = new A<Y>(new A<Y>.Delegate() {
  @Override
  public void doMagic(Y y) {
    ...
  }
});

Why can't I access T from Delegate interface?

Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111

2 Answers2

6

It's because your inner interface is static. The generic parameter only applies to an instance of A as opposed to applying to the class, so the scope of T is the non-static scope of A.

In case you didn't know, all interfaces and enumerations are static in Java, even if they are not declared as static and are inside another class. Therefore there is no way to work around this with an interface.

See this answer also.

EDIT: Steven's answer is correct. However, your user code will look like this:

// Note the extra declaration of the generic type on the Delegate.
A<Integer> a = new A<Integer>(new A.Delegate<Integer>() {
  @Override
  public Integer myMethod() {
    return null;
  }
});
Community
  • 1
  • 1
5

Your inner interface can have its own generic bounds. Try declaring and using it as Delegate<T> and it should work fine.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 2
    It's worth noting that the `` won't be the same, but it will be typesafe if the constructor signature is changed to `public A(Delegate delegate)` –  Oct 25 '11 at 08:32