Question about generic method - see code snippet and error
Posted: Wed Oct 14, 2015 9:00 pm
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");
}
}
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