public class MyGenericClass< G> {
public <G> G genericMethod1(G g){
System.out.println(g.toString());
return g;
}
public <X> G genericMethod2(G g) {
System.out.println(g.toString());
return g;
}
public <X> X genericMethod3(G g) {
System.out.println(g.toString());
Integer i = new Integer(100);
return (X) i;
}
public static void main(String... cmdarg) {
MyGenericClass<Employee> gemp = new MyGenericClass<Employee>();
Employee e1 = new Employee();
e1.setName("My Name");
String resultOfMethod3 = gemp.genericMethod3(e1);
System.out.println(resultOfMethod3);
}
}
in genericMethod1: I get the compiler warning as "The type parameter G is hiding the type G".
Question:
Which G is hidden by this G? What's the actual meaning of this?
genericMethod2 doesn't show any errors/warnings.
Question:
I thought it should not compile. why is two different types allowed in same method signature? What can be typical real time example to compare with G and X?
In genericMethod3: I'm intentionally returning an Integer object and in the main method i'm trying to assign the result to a String. As expected: I got the ClassCastException.
Question: Isn't the original purpose of having generics to avoid ClassCastExceptions? Why did the compiler allow it? Is this a bug in the design of Generics?
Copyright Notice:Content Author:「Jinnah」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32820133/the-type-parameter-g-is-hiding-the-type-g