Does the generic constructor of the inner class accept a type parameter that is set?

Sorry for the confusing question, but I cannot find an easier way to ask about this. I am currently experimenting with generics and encountering something that I can’t wrap my head around. I have a common class with a type parameter Tand it has a common inner class with a type parameter E. However, an internal class constructor is required T.

If I instantiate an outer class using, say, Outer<String>and instantiate an inner class using <Integer>and call its constructor using an integer, there is no problem. This does not make any sense to me, since in this case the constructor should only work with String, as set in the type parameter Outer. Why is this so?

If I create a method in an inner class that requires T, though The method method(T) in the type Outer<T>.InnerGeneric<Integer> is not applicable for the arguments (int), that makes sense to me. Why does this not happen with the constructor method?

Here is a snippet of my code:

public class Outer<T> { 
    class InnerGeneric<E> { 
        InnerGeneric(T t) {
            //do something
        }

        void method(T t) {
            //do something
        }
    }

    class Inner {
    }

    Outer(T t) {
        InnerGeneric<T> inner1 = new InnerGeneric<>(t); 
        InnerGeneric<Integer> inner2 = new InnerGeneric<>(1); //i do not get any error here, 
                                                                and the code can run just                                                                 
                                                                fine with this, why???

        inner2.method(t);   
        inner2.method(1); //get a compilation error here, this makes sense to me   
    }

    public static void main(String[] args) {
        Outer<String> outer = new Outer<>("Any string");        
    }
}

EDIT: I'm using Eclipse, not sure what this means in terms of which version of javac, since I'm still pretty new to this.

+4
1

javac 1.8.0_25, , , Eclipse . ( , , Eclipse, .)

Eclipse, , . InnerGeneric<Integer> inner2 = new InnerGeneric<Integer>(1);, Eclipse .

( , , Eclipse, .)

+3

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


All Articles