Java OCA OCP Practice Question 2957

Question

Given:

2. class Shape {  
3.   static String s = "";  
4.   void doShape() { s += "bounce "; }  
5. }  //from www. j  a  v  a2s.c  o  m
6. class Rectangle extends Shape {  
7.   void doShape() { s += "swish "; }  
8. }  
9. public class Main extends Shape {  
10.   public static void main(String[] args) {  
11.     Shape b = new Main();  
12.     Rectangle bb = (Rectangle)b;  
13.     b.doShape();  
14.     bb.doShape();  
15.     System.out.println(s);     
16.   }  
17.   void doShape() { s += "fore "; }  
18. } 

What is the result?

  • A. fore fore
  • B. fore swish
  • C. bounce swish
  • D. bounce bounce
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


F   is correct.

Note

On line 12, a ClassCastException is thrown.

Variable b refers to a subtype (Main), and it can be cast only to another Main reference variable.




PreviousNext

Related