Given these classes:
and this the code fragment:
What is the result?
Given these classes:
and this the code fragment:
What is the result?
The program throws an exception. The line A[] values = new B[2]; creates an array of type B, which means it expects to hold objects of type B or subclasses of B. When values[0] = new C(); is executed, it attempts to store an object of type C in an array that is specifically an array of Bs, and since C is not a subclass of B, an ArrayStoreException is thrown at runtime.
answer: A A[] values = new B[2]; 5.1.6. Narrowing Reference Conversion From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a narrowing reference conversion from SC to TC. So that's ok because B extends A. values[0] = new C(); [2] The compiler guarantees that when you take an element from an array, it will be representative of the element type of the array itself. It doesn't matter what type the variable stores it. Values is the array of type B. That's way there is an ArrayStoreException.
A[] a= new B[2]; => an array a that is reference to B array B is a subclass of A=> that is valid a[0] = new C()-> thown exception because real object o a is b type, and C is not subtype of B. IF A[] a = new A[2]; => then compile ok beacuse b and c are subclass of A
A is correct throw ArrayStoreException, because its declare to store new B[2], can contains only B elements ohttps://www.examtopics.com/exams/oracle/1z0-819/view/40/#r his subclasess, so C is not subclase of B cannot asing