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]; // **?!**
4
  • 2
    Try it by using a compiler. Commented Feb 20, 2013 at 18:36
  • What is the output you get and what is the output you expect? Commented Feb 20, 2013 at 18:36
  • 1
    "but I can't understand why this happen"... What happens? Commented Feb 20, 2013 at 18:38
  • I can use a compiler , but I want to understand why ? to learn more about the dynamic aspects of the language . Commented Feb 20, 2013 at 18:40

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.