Java OCA OCP Practice Question 132

Question

Given the following:

1. class X { void actionA() { } } 
2. class Y extends X { void actionB() { } } 
3. /*from  w  ww . j  av a2s .  co m*/
4. class Main { 
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. } } 

Which of the following, inserted at line 9, will compile? (Choose all that apply.)

  • A. x2.actionB();
  • B. (Y)x2.actionB();
  • C. ((Y)x2).actionB();
  • D. None of the above statements will compile


C is correct.

Note

Before you can invoke Y's actionB method, you have to cast x2 to be of type Y.

A, B, and D are incorrect based on the preceding.

B looks like a proper cast, but without the second set of parentheses, the compiler thinks it's an incomplete statement.




PreviousNext

Related