Java OCA OCP Practice Question 2817

Question

Given

2. class MyClass {   
3.   static String s = "";  
4.   void print() { s += "trot "; }  
5. }  /*  ww  w .  j  a  v a2s .c o  m*/
6. public class Main extends MyClass {  
7.   void print() { s += "tolt "; }  
8.   public static void main(String[] args) {  
9.      MyClass x0 = new MyClass();  
10.     MyClass x1 = new Main();  x1.print();  
11.     Main x2 = (Main)x1;     x2.print();   
12.     Main x3 = (Main)x0;     x3.print();  
13.     System.out.println(s);  
14. } } 

What is the result?

  • A. tolt tolt tolt
  • B. trot tolt trot
  • C. trot tolt tolt
  • D. Compilation fails.
  • E. An exception is thrown at runtime.


E is correct.

Note

On line 12, the code attempts to cast a MyClass reference (the superclass) to an Main reference, causing a ClassCastException.




PreviousNext

Related