Java OCA OCP Practice Question 2079

Question

Consider the following program:.

class Base {}//  w ww.  j a  v a  2  s .  c  o m
class DeriOne extends Base {}
class DeriTwo extends Base {}

public class Main {
     public static void main(String []args) {
             Base [] baseArr = new DeriOne[3];
             baseArr[0] = new DeriOne();
             baseArr[2] = new DeriTwo();
             System.out.println(baseArr.length);
     }
}

Which one of the following options correctly describes the behavior of this program?.

  • A. this program prints the following: 3
  • B. this program prints the following: 2
  • C. this program throws an ArrayStoreException
  • D. this program throws an ArrayIndexOutOfBoundsException


C.

Note

The variable baseArr is of type Base[], and it points to an array of type DeriOne.

In the statement baseArr[2] = new DeriTwo(), an object of type DeriTwo is assigned to the type DeriOne, which does not share a parent-child inheritance relationship-they only have a common parent, which is Base.

This assignment results in an ArrayStoreException.




PreviousNext

Related