Java Generics: non-static type variable T cannot be referenced from a static context

13,311

Solution 1

All member fields of an interface are by default public, static and final.

Since inner interface is static by default, you can't refer to T from static fields or methods.

Because T is actually associated with an instance of a class, if it were associated with a static field or method which is associated with class then it wouldn't make any sense

Solution 2

How about something like this.

public interface A<T> {

     interface B<T> extends A<T>{

       T foo(); 
    }

}
Share:
13,311

Related videos on Youtube

auser
Author by

auser

Updated on September 15, 2022

Comments

  • auser
    auser over 1 year
    interface A<T> {
    
        interface B {
           // Results in non-static type variable T cannot
           // be referenced from a static context
           T foo(); 
        }
    
    }
    

    Is there anyway round this? Why is T seen as static when referenced from A.B?

  • auser
    auser almost 12 years
    Thanks, that answers the first part of the question. How do I get the type T seen in the inner interface to be the same type at that of the containing interface?
  • Paul Bellora
    Paul Bellora almost 12 years
    I would remove the first sentence as it's unnecessary and misleading - yes interface fields are implicitly public static final but this has to do with interface methods which are implicitly public abstract. The fact that inner interfaces are implicitly static themselves is what's important.
  • jmj
    jmj almost 12 years
    well inner interface is same as inner field
  • Josie Thompson
    Josie Thompson almost 4 years
    Isn't the T in B<T> a different T than in A<T> here?