Compilation error for Generic class with common interface

In my understanding, the following code should work without any compilation error.

However, when I run this program, I get the following compilation error.

The BD member type cannot be qualified with a parameterized type because it is static. Remove arguments from qualifying type B

class B<X> {
    interface C {
    }

    interface D<Y> {
    }
}

class Test {
     // compilation fails here
    B<String>.D<String>[] arr = new B<String>.D<String>[10];
}

      

Please help me understand this behavior.

+3


source to share


3 answers


Like an inner class static

, a nested interface has no connection to an instance of its outer class, but only to the class itself. All members static

are shared among all instances B

, regardless of the type parameter B

. Consider:

class B<T> {
    public static int shared = 0;
}

      

The variable shared

is the same in the B<String>

, B<Integer>

, B<Object>

and so on. Trying to access it parameterized B

results in a compilation error:



int copy = B<String>.shared; // <<== Does not compile

      

Hence, the type parameter has B

no effect on the declaration arr

, which is why Java wants you to remove it:

B.D<String>[] arr = new B.D[10];

      

+4


source


First of all, you can choose not to create arrays of specific parameterized types. Example:

Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal 

      

does not work. See here for details .

But it looks like the compiler is giving you a different, less useful error message here because it first stumbled upon the fact that nested interfaces are like static inner classes.



So the only thing you can do is ignore the generic type in the rhs of the job:

B.D<String>[] arr = new B.D[10];

      

which, of course, leads to a security type warning, and makes the whole idea of ​​this internal interface kind of obsolete.

So the real answer is probably: generics and arrays don't mix well in Java - don't use them in the first place. And don't be surprised that the complication of the situation leads to the fact that the search results in the interface are even less "pleasant user experience".

+2


source


Internal interfaces are always static

(as opposed to classes). Therefore, the parameter String

for B is meaningless in the definition new B<String>.D<String>

.

+1


source







All Articles