Given the following, 1. class X { void dol() { } } 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. } Which, inserted at line 9, will compile? (Choose all that apply.)

  1. x2.do2( );

  2. (Y) x2. do2( );

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

  4. None of the above statements will compile.


Correct Option: C
Explanation:

To solve this question, the user needs to know about method invocation and upcasting/downcasting in Java.

Line 6 creates a new instance of class X. Line 7 creates a new instance of class Y and assigns it to a reference variable of type X. Line 8 creates a new instance of class Y.

At line 9, we need to insert code that will compile. Since the reference variable x2 is of type X, it does not have access to the method do2() that is defined in class Y. However, we know that x2 refers to an object of class Y, which does have access to the do2() method. Therefore, we need to cast x2 to type Y in order to access the do2() method.

Now, let's go through each option and explain why it is right or wrong:

A. x2.do2( ); - This option is incorrect because the reference variable x2 is of type X, which does not have access to the do2() method that is defined in class Y.

B. (Y) x2. do2( ); - This option is incorrect because the cast operator (Y) is applied to the method call, not to the reference variable x2. This is not valid syntax.

C. ((Y)x2).do2(); - This option is correct. The cast operator is applied to the reference variable x2, casting it to type Y. This allows us to access the do2() method that is defined in class Y.

D. None of the above statements will compile. - This option is incorrect because option C will compile.

Therefore, the correct answer is:

The Answer is: C. ((Y)x2).do2();

Find more quizzes: