Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use generics in an inner interface?

Tags:

java

static

I tried to compile the following code:

public interface Foo<T> {
    public interface Bar {
        public void bar(T t);
    }

    void foo(T t);
}

But I get this error: "Foo.this cannot be referenced from a static context."

Specifically, I get it on the "T" in bar(T t). However foo(T t) does not produce the same error. I don't understand why that's a static context and what the error really means.

like image 984
Barry Fruitman Avatar asked Dec 18 '14 18:12

Barry Fruitman


People also ask

Can we use generic in interface?

8. Java Generic Classes and Subtyping. We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

What are the restrictions on generics?

Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.

Why should we avoid generics in Java?

Many people are unsatisfied with the restrictions caused by the way generics are implemented in Java. Specifically, they are unhappy that generic type parameters are not reified: they are not available at runtime. Generics are implemented using erasure, in which generic type parameters are simply removed at runtime.


1 Answers

A "nested" interface (Bar in your example) is implicitly static. So it can't access instance specific information related to Foo, such as its generic type.

See for example JLS #8.5.1:

A member interface is implicitly static

like image 114
assylias Avatar answered Oct 12 '22 14:10

assylias