0

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 ?

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

B[] bs = new B[10];
f(bs); // **?!**
B b = bs[0]; // **?!**
nabil
  • 874
  • 1
  • 11
  • 28

1 Answers1

2

Arrays in Java is covariant.

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.

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
Bhesh Gurung
  • 48,464
  • 20
  • 87
  • 139