Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Q#14 of Diagnostic

Hi,


It is stated as correct answer A & B for this question. A I understand why. But the explanation for option B it seems not correct. Since C extends B it should not be any problem. Right?


Thank you for your time.

Hi Rebeca,


Our class structure is:


  class A{}
  class B extends A{}
  class C extends B{}
  class D extends C{}


And the code we have for the option B is:


A[] a=new C[1];
a[0] = new B();


As said in the explanation provided, there are two requirements that need to be fulfilled at the second line of the above code for it to run with no problem.


At the compile time, the value you assign to a[0] must either be the reference type of the array (A), or a sub-type of it (B,C,D). If not, compilation would fail

At the run time, the value you assign to a[0] must either be the object type of the array (C), or a sub-type of it (D). If not, ArrayStoreException would be thrown


In the above code, the second requirement fails, because the object we pass is 'B', which is not a sub-type of C. So it throws ArrayStoreException.


You are correct that C extends B, which means C is a sub-type of B. But that doesn't matter, because what it looks for is the other way around - B needs to extend C.


Does that make it clear?

Hi,


Thank you for the prompt reply. Now since is sliced into each step now is much clear as it was.


Thank you

ExamLab © 2008 - 2024