Multiple choice technology programming languages

  1. class X { void do1() { } } 2. class Y extends X { void do2() { } } 3. 4. class Chrome { 5. public static void main(String [] args) { 6. X x1 = new X(); 7. X x2 = new Y(); 8. Y y1 = new Y(); 9. // insert code here 10. } 11. }

  1. x2.do2();

  2. (Y)x2.do2();

  3. ((Y)x2).do2();

  4. None of the above statements will compile

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The reference x2 has compile-time type X but points to a Y object. Since do2() is only defined in Y, we must downcast x2 to Y before calling it. Option C correctly applies the cast before the method call with ((Y)x2).do2(). The extra parentheses ensure casting occurs first.