Java OCA OCP Practice Question 2624

Question

Consider the following program:

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

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 MainException.
  • 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.

Hence, this assignment results in an MainException.




PreviousNext

Related