I have a Student class and a StudentPool class defined as follows:
public class Student {
public Student copy () {
return new Student();
}
}
and
public class StudentPool<T extends Student> {
public T copyStudent(T t) {
return t.copy();
}
}
thus, the copyStudent method cannot be compiled and I have to use un-safe type casting. I cannot understand why Java does regard this as illegal?
Edit:
user845279, lcfseth, and Bohemian: I think the following revision to Student may cause the similar scenario, cast a parent class into its child class, but this version can pass compiling:
public class Student {
public <T extends Student> T copy() {
T rv = null;
return rv;
}
}
Edit:
forget the above code: rv can be either null or un-safely casted.
The problem is that although
StudentreturnsStudentfromcopy(), subclasses would also returnStudent… not their own type.Here’s an approach to fix your problem:
As a side note, it seems you don’t need generics here.