Java OCA OCP Practice Question 221

Question

Diagram://  w w w .  j  ava2  s.c  o m

                       Animal 
                         |
                       Mammal
                         |
 +----------------+------+--------+----------------+
 |                |               |                |
                 Cat           Raccoon           Fish 
Dog         (implements      (implements          
              Washer)          Washer) 

Consider the following code:

1. Raccoon rocky; 
2. Fish myFish; 
3. Washer w; 
4. 
5. rocky = new Raccoon(); 
6. w = rocky; 
7. myFish = w; 

Which of the following statements is true? (Choose one.)

  • A. Line 6 will not compile; an explicit cast is required to convert a Raccoon to a Washer.
  • B. Line 7 will not compile; an explicit cast is required to convert a Washer to a Fish.
  • C. The code will compile and run.
  • D. The code will compile but will throw an exception at line 7, because runtime conversion from an interface to a class is not permitted.
  • E. The code will compile but will throw an exception at line 7, because the runtime class of w cannot be converted to type Fish.


B.

Note

The conversion in line 6 is fine (class to interface), but the conversion in line 7 (interface to class) is not allowed.

A cast in line 7 will make the code compile, but then at runtime a ClassCastException will be thrown, because Washer and Fish are incompatible.




PreviousNext

Related