Compilation of generic class using generic interface failed
•
Java
As far as I know, the following code should run without any compilation errors
However, when I run this program, I get the following compilation errors
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
Solution
In a way similar to an internal static class, a nested interface is not associated with an instance of its external class, but only with the class itself All static members are shared among all instances of B regardless of the type parameters of B consider:
class B<T> { public static int shared = 0; }
Variable sharing is the same in B < string >, B < integer >, and B < Object > wait. Attempting to access it on parameterized B will result in a compilation error:
int copy = B<String>.shared; // <<== Does not compile
Therefore, the type parameter of B has no effect on the declaration of arr, so Java wants you to delete it:
B.D<String>[] arr = new B.D[10];
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码