Multiple choice technology programming languages

Click the Exhibit button. 1. public interface A { 2. public void doSomething(String thing); 3. } 1. public class AImpl implements A { 2. public void doSomething(String msg) { } 3. } 1. public class B { 2. public A doit() { 3. // more code here 4. } 5. 6. public String execute() { 7. // more code here 8. } 9. } 1. public class C extends B { 2. public AImpl doit() { 3. // more code here 4. } 5. 6. public Object execute() { 7. // more code here 8. } 9. } Which statement is true about the classes and interfaces in the exhibit?

  1. Compilation will succeed for all classes and interfaces.

  2. Compilation of class C will fail because of an error in line 2.

  3. Compilation of class C will fail because of an error in line 6.

  4. Compilation of class AImpl will fail because of an error in line 2.

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

Class C's doit() method is valid because AImpl is a subclass of A, which is a valid covariant return type (narrowing the return type). However, execute() fails because you cannot widen a return type from String to Object when overriding - overriding methods must return the same type or a subtype, not a supertype. Option C correctly identifies line 6 as the compilation error.

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Compilation will succeed for all classes and interfaces. This option is incorrect. The compilation will not succeed for all classes and interfaces because there are errors in the code.

Option B) Compilation of class C will fail because of an error in line 2. This option is incorrect. There is no error in line 2 of class C. Line 2 in class C is a valid method declaration that overrides the method in class B.

Option C) Compilation of class C will fail because of an error in line 6. This option is correct. Line 6 in class C is attempting to override the method execute() from class B, but the return type of the overridden method in class C is Object, which is not compatible with the return type String in class B. This will result in a compilation error.

Option D) Compilation of class AImpl will fail because of an error in line 2. This option is incorrect. There is no error in line 2 of class AImpl. Line 2 is a valid method implementation that matches the method declaration in interface A.

The correct answer is C. Compilation of class C will fail because of an error in line 6.