Paul Clapham wrote:Line 15 has the error because the compiler can't guarantee that R is a superclass of String under all circumstances.
And the fact that you create a Generic1<String> object at line 19, thus identifying T with String for that particular line of code, doesn't even have anything to do with the type parameter R on the aMethod() method, but even if you'd used T there instead of R it still wouldn't have made any difference because there's nothing in your declaration of the Generic1 class which guarantees that T is a superclass of String either.
Paul Clapham wrote:The compiler can't do any inferring on a class which doesn't even compile. As I said, there's no way for the compiler to confirm that R is always a superclass of String, so your Generic1 class can't compile.
And even if it did compile, the R parameter of the aMethod method wouldn't have anything to do with creating a Generic1 object -- that's the constructor which would be involved, not the aMethod method.
Sergei Zhylinski wrote:Hi,
Your code leads to an evident compile time error. Your type parameter 'R' says that the generic method can take any type argument, 'String', 'CharSequence', 'Number', 'Object'. Lets simplify your code with only one type parameter. I'll create a method inside a regular class:
I explicitly say that the generic method has a bounded type parameter 'R extends Object'. Also I explicitly provide a type argument 'Number' to my generic method. As you can see not only strings can be passed to the generic method. It doesn't matter if the generic method is invoked inside class definition or outside it.
Kirk Rohani wrote:
I don't understand why I can create SomeClass<T> and pass in a string literal into the constructor and assign it to a variable of type <T> and it infers/figures out that it is a string but as you proved I cannot create a generic method and assign a string literal it to a variable of type <R>.
That is really what I am wanting to understand, why it works with a generic class but not a generic method??
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |