Java OCA OCP Practice Question 3246

Question

Consider the following program and choose the correct option from the list of options:

class Base {//from ww w  . j  av  a  2  s .  c  om
     public void test() {}
}

class Base1 extends Base {
     public void test() {
             System.out.println("Base1");
     }
}

class Base2 extends Base {
     public void test() {
             System.out.println("Base2");
     }
}

class Test {
     public  static void main(String[] args) {
             Base obj = new Base1();
             ((Base2)obj).test();    // CAST
     }
}
  • a) The program will print the following: Base1.
  • b) The program will print the following: Base2.
  • c) The compiler will report an error in the line marked with comment CAST.
  • d) The program will result in an exception (ClassCastException).


d)

Note

The dynamic type of variable obj is Base1 that you were trying to cast into Base2.

This is not supported and so results in an exception.




PreviousNext

Related