Inner class type parameter associated with the inclusion of a class type variable

Is it possible to use a type variable declared by the enclosing class as a binding for a type variable declared in the inner class?

class Test<E> {
   class Inner<T extends E> {}
   <T extends E> void doStuff(T arg) {}
   public static void main(String[] args) {
      new Test<Number>().doStuff(new Integer(0)); // works fine, as expected
      new Test<Number>().new Inner<Integer>(); // won't compile
   }
}

javac gives this error:

Test.java:6: type parameter java.lang.Integer is not within its bound
             new Test<Number>().new Inner<Integer>();
                                             ^

I can not find a combination of types that will satisfy the compiler. What is the difference between a type parameter Tdeclared Innercompared to doStuff? Why does one work and the other not?

I'm not looking for alternatives, I just want to better understand how the language works.

+3
source share
1 answer

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6557954

Bug ID: 6557954
Votes   2
Synopsis    Inner class type parameters doesn't get substituted when checking type well-formedness
Category    java:compiler
Release Fixed    7(b40)
State   10-Fix Delivered, bug
Priority:   5-Very Low
Submit Date 16-MAY-2007
Posted Date : 2008-07-02 16:22:46.0

Description

The compiler cannot accept this program:

class Foo<T> {
  class Bar<U extends T> {}
  Foo<Number>.Bar<Integer> f;
}

Rating

Check.java, . Foo.Bar T = Number, U = Integer

, :

Number <: Object
Integer <: [Number/T]T = Number

, javac , :

Integer <: T 

.

Edit:

Java 7 javac:

C:\workspace\Sandbox\src>"%JAVA_HOME%\bin\javac.exe" -version
javac 1.7.0-ea

, Java 6 javac:

C:\workspace\Sandbox\src>"%JAVA_HOME%\bin\javac.exe" -version
javac 1.6.0_17
+3

Source: https://habr.com/ru/post/1788359/


All Articles