Java多态互相排列子类型

时间:2022-06-28 19:40:27

I know that Java is static language, and there is dynamic check when it comes to arrays : but I can't understand why this happen, can someone explain to me this example in both cases when : A[] is sub-type to B[], or B[] is sub-type to A[] ? which will fail and why ?

我知道Java是静态语言,并且在数组方面有动态检查:但是我无法理解为什么会发生这种情况,有人可以在这两种情况下向我解释这个例子:A []是B的子类型[],或者B []是A []的子类型?哪个会失败,为什么?

f(A[] as) {
  as[0] = new A(); // **?!**
}

B[] bs = new B[10];
f(bs); // **?!**
B b = bs[0]; // **?!**

1 个解决方案

#1


2  

Arrays in Java is covariant.

Java中的数组是协变的。

Which means if B is a subtype of A then B[] is also a subtype of A[]. So, you can pass a B[] where A[] is expected just like you can pass a B where an A is expected.

这意味着如果B是A的子类型,那么B []也是A []的子类型。所以,你可以传递一个B [],其中A []是预期的,就像你可以通过一个预期A的B一样。

But if you go the opposite way then you would need an explicit cast like -

但如果你采取相反的方式,那么你需要一个明确的演员,如 -

 B b = (B) new A(); //bypasses the compiler but fails at runtime
 B[] bs = (B[]) new A[1]; //also bypasses the compiler but fails at runtime

#1


2  

Arrays in Java is covariant.

Java中的数组是协变的。

Which means if B is a subtype of A then B[] is also a subtype of A[]. So, you can pass a B[] where A[] is expected just like you can pass a B where an A is expected.

这意味着如果B是A的子类型,那么B []也是A []的子类型。所以,你可以传递一个B [],其中A []是预期的,就像你可以通过一个预期A的B一样。

But if you go the opposite way then you would need an explicit cast like -

但如果你采取相反的方式,那么你需要一个明确的演员,如 -

 B b = (B) new A(); //bypasses the compiler but fails at runtime
 B[] bs = (B[]) new A[1]; //also bypasses the compiler but fails at runtime