Multiple choice technology programming languages

Given: 10. class One { 11. public One foo() { return this; } 12. } 13. class Two extends One { 14. public One foo() { return this; } 15. } 16. class Three extends Two { 17. // insert method here 18. } Which two methods, inserted individually, correctly complete the Three class? (Choose two.)

  1. public void foo() { }

  2. public int foo() { return 3; }

  3. public Two foo() { return this; }

  4. public Object foo() { return this; }

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

When overriding methods, the return type can be a subtype (covariant return), but not a supertype or unrelated type. Option C works because Two is a subclass of One, making it a valid covariant return type. Option A (void) and B (int) have incompatible return types, and D (Object) attempts to widen the return type.

AI explanation

An overriding method may narrow its return type to a subtype of the overridden method's return type (covariant return), but never widen it to a supertype. Two.foo() returns One, so Three's override must return One, Two, or Three. 'public Two foo() { return this; }' is valid because Two is a subtype of One and 'this' (a Three) is-a Two. 'public Object foo()' fails to compile because Object is a supertype of One, and void/int variants are not overrides at all — so only one of the listed methods is actually a legal completion.