我有一个 Student
类和一个 StudentPool
类,定义如下:
public class Student {
public Student copy () {
return new Student();
}
}
和
public class StudentPool<T extends Student> {
public T copyStudent(T t) {
return t.copy();
}
}
因此,copyStudent
方法无法编译,我必须使用不安全的类型转换。我不明白为什么 Java 会认为这是非法的?
编辑: user845279、lcfseth 和 Bohemian:我认为以下对 Student 的修改可能会导致类似的情况,将父类转换为其子类,但此版本可以通过编译:
public class Student {
public <T extends Student> T copy() {
T rv = null;
return rv;
}
}
编辑:
忘记上面的代码:rv
可以是 null
或非安全转换。
最佳答案
假设你有一个类 SmartStudent
扩展Student
, 和一个 StudentPool<SmartStudent>
.在这种情况下 copyStudent
应该采取 SmartStudent
并返回 SmartStudent
,但是 Student
中的实现没有这样做 - 它只返回一个普通的 Student
实例。
编辑:
为了实现你想要的模式,你可以给出 Student
及其所有子类 a copy constructor :
public class Student {
public Student(Student other) {
//copy other's Student fields to this instance
}
}
public class SmartStudent extends Student {
public SmartStudent(SmartStudent other) {
super(other);
//copy other's SmartStudent fields to this instance
}
}
并制作StudentPool
摘要:
public abstract class AbstractStudentPool<T extends Student> {
public T copyStudent(T original);
}
每个AbstractStudentPool
实现将调用适当的复制构造函数:
public class SmartStudentPool extends AbstractStudentPool<SmartStudent> {
@Override
public SmartStudent copyStudent(SmartStudent original) {
return new SmartStudent(original);
}
}
关于java - 我的泛型类型转换有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10544229/