Java OCA OCP Practice Question 201

Question

Refer to the class hierarchy shown in the graphic below.

Diagram:/*from  ww  w. ja v a  2  s .c  o m*/

                       Animal 
                         |
                       Mammal
                         |
               +---------+------+
               |                |              
              Dog              Cat           
                                       
                                          

Consider the following code:

1. Dog      rover, fido; 
2. Animal   anim; 
3. 
4. rover = new Dog(); 
5. anim = rover; 
6. fido = (Dog)anim; 

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

  • A. Line 5 will not compile.
  • B. Line 6 will not compile.
  • C. The code will compile but will throw an exception at line 6.
  • D. The code will compile and run.
  • E. The code will compile and run, but the cast in line 6 is not required and can be eliminated.


D.

Note

The code will compile and run.

The cast in line 6 is required, because changing an Animal to a Dog is going "down" the tree.




PreviousNext

Related