Page 1 of 1

Question about generic method - see code snippet and error

Posted: Wed Oct 14, 2015 9:00 pm
by krohani

Code: Select all

public final class Generic1<T>
{
    T genVar;
 
    public Generic1(T passedIn)
    {
        genVar = passedIn;
        System.out.println("Inside Generic1 constructor: " + genVar);
        aMethod("hello!!");
    }
 
    public <R> void aMethod(R action)
    {
        System.out.println("action passed in: " + action);
        R myIntOrString = "string";
    }
    public static void main(String... args)
    {
        Generic1<String> mygen = new Generic1<>("passing soemthing in");
    }
}
I understand why the above code snippet will not compile. I get the following compile error:

javac Generic1.java
Generic1.java:15: error: incompatible types: String cannot be converted to R
R myIntOrString = "string";
^
where R is a type-variable:
R extends Object declared in method <R>aMethod(R)
1 error

What I don't understand is the WHY? I thought that since I am calling aMethod and passing in a String that the compiler would infer that R is of type String and allow the assignment R myIntOrString = "string"

Someone please tell me what concept I am not understanding about generics.

Thanks!
Kirk

Re: Question about generic method - see code snippet and err

Posted: Wed Oct 14, 2015 9:46 pm
by admin
Because at the time of compilation the compiler cannot be certain what is R being typed to in relation to T. Remember that a compiler doesn't execute code. So when it sees Generic1<String> mygen = new Generic1<>("passing soemthing in");, it types T to String because you have explicitly specified <String> there.

But it doesn't execute the constructor. Therefore, it doesn't know what is R typed to.