The problem happens because of what lealceldeiro mentions in a comment: you have specified a type parameter on the class as well as on the method. These are both named T
, but they are separate type parameters, so they are really different.
public class GenericVariables<T> { // Type parameter <T> on class here
private T page;
public void main (String args[]) {
setGenericVar(2);
}
// Type parameter <T> on method here
public <T> void setGenericVar(T page) {
this.page = page;
}
}
If you give them different names, it will be easier to see what's going on:
public class GenericVariables<T> {
private T page;
public void main (String args[]) {
setGenericVar(2);
}
public <U> void setGenericVar(U page) {
// ERROR: this.page is of type T, but the parameter page is of type U
this.page = page;
}
}
Solution: Remove the type parameter from the method; just let it use the type parameter of the class.
public class GenericVariables<T> {
private T page;
public void main (String args[]) {
setGenericVar(2);
}
public void setGenericVar(T page) {
this.page = page;
}
}
Note: Your main
method is not static
, therefore Java will not see this as the entry point for your program; you cannot run your program starting from this main
method. You need to make it static
. If you do that, you cannot call the setGenericVar
method directly. You'll need to create an instance of the class and call the method on that:
public class GenericVariables<T> {
private T page;
public static void main (String args[]) {
GenericVariables<Integer> object = new GenericVariables<>();
object.setGenericVar(2);
}
public void setGenericVar(T page) {
this.page = page;
}
}