Java OCA OCP Practice Question 138

Question

Given:

3. public class Dog extends Animal { 
4.   public static void main(String[] args) { 
5.     new Dog().go(); 
6.   } /*from w  w  w.  j  a v a 2 s.  c  o  m*/
7.   void go() { 
8.     go2(new Animal(), new Dog()); 
9.     go2((Dog) new Animal(), new Dog()); 
10.   } 
11.   void go2(Animal t1, Dog r1) { 
12.      Dog r2 = (Dog)t1; 
13.      Animal t2 = (Animal)r1; 
14.   } 
15. } 
16. class Animal { } 

What is the result? (Choose all that apply.)

  • A. An exception is thrown at runtime
  • B. The code compiles and runs with no output
  • C. Compilation fails with an error at line 8
  • D. Compilation fails with an error at line 9
  • E. Compilation fails with an error at line 12
  • F. Compilation fails with an error at line 13


A is correct.

Note

A ClassCastException will be thrown when the code attempts to downcast a Animal to a Dog.




PreviousNext

Related