Question about generic method - see code snippet and error

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
krohani
Posts: 31
Joined: Tue Oct 06, 2015 1:57 pm
Contact:

Question about generic method - see code snippet and error

Post 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

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests