基类有一个数据成员,它是一个对象数组 A[]
和一个访问器方法。我希望能够覆盖访问器以返回 B[]
,其中 B
是 A
的子类。
在 Java 5.0 中,它允许我这样做,因为数组是协变的,但我得到一个 当我尝试执行以下操作时出现 ClassCastException:
class Business {
A[] clients;
A[] getClientList() { return clients; }
}
class DoctorBusiness extends Business {
B[] getClientList(){
return super.clients;
//this line thwoes a classcastexception
}
}
其中 Client 对应于 A,Patient 对应于 B,Patient extends Client。
我该如何解决这个问题?我知道数组中的所有对象都将是 B
类型,并且希望避免每次访问客户端的数组元素时都必须转换为 Patient
最佳答案
只是怎么样
class A{}
class B extends A{}
public class Test<T extends A> {
T[] t;
public T[] get()
{
return t;
}
public static void main(String args[])
{
Test<B> t2 = new Test<B>();
B[] b = t2.get();
}
}
关于java - 在数组中正确使用协方差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981987/