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. } Which, inserted at line 9, will compile? (Choose all that apply.)
  1. (Y)x2.do2();

  2. 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 inheritance, method overriding, and type casting.

In the given code, class X defines a method do1() and class Y extends class X and includes a new method do2(). In the main method, three objects are created, x1 is an object of class X, x2 is a reference of class X that points to an object of class Y, and y1 is an object of class Y.

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

A. (Y)x2.do2(); This option will not compile because x2 is a reference of class X and does not have access to the method do2() of class Y. To call a method of a subclass, we need to cast the reference to that subclass. However, we cannot cast x2 to class Y because it is not an object of class Y.

B. x2.do2(); This option will not compile because the reference x2 is of class X and does not have access to the method do2(). Since x2 is a reference of class X, only the methods defined in class X or its superclasses can be called using this reference.

C. ((Y)x2).do2(); This option will compile because we are casting the reference x2 to class Y, which has access to the do2() method. Since x2 is pointing to an object of class Y, we can safely cast it to class Y. The casted reference ((Y)x2) can then access the do2() method of 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: