Aaron Barnard
Aaron Barnard

Reputation: 127

Generic inner class constructor accepts different type parameter what is set?

Apologies for the convoluted question, but I can't figure out an easier way to ask it. I am currently experimenting with generics and have run into something I cannot wrap my head around. I have a generic class with type parameter T and it has a generic inner class with type parameter E. However, the inner class' constructor requires a T.

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

If I create a method in the inner class that requires a T, though, The method method(T) in the type Outer<T>.InnerGeneric<Integer> is not applicable for the arguments (int) which does make sense to me. How come this does 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 am using Eclipse, not sure about what that means in terms of what version of javac, as I am still fairly new to it all

Upvotes: 4

Views: 140

Answers (1)

biziclop
biziclop

Reputation: 49744

I tried it with javac 1.8.0_25 and it gives a compilation error, as you'd correctly expect, while Eclipse indeed does not. (I assume from the error message you quoted that it is Eclipse you're working with.)

This seems like a bug in the Eclipse compiler, specifically with the handling of the diamond operator. If you replace that line with InnerGeneric<Integer> inner2 = new InnerGeneric<Integer>(1); then Eclipse rejects it too.

(Though my search skills aren't very good, as far as I can tell it hasn't been logged yet as an Eclipse bug, so you should probably report it.)

Upvotes: 3

Related Questions