Tuesday, August 24, 2010

Covariant Returns: SuperFoo.java

Courtesy of Sun Web Learning Center

Given:

1. class SuperFoo {
2.   SuperFoo doStuff(int x) {
3.     return new SuperFoo();
4.   }
5. }
6.
7. class Foo extends SuperFoo {
8.   // insert code here
9. }

Which three, inserted independently at line 8, will compile? (Choose three.)


A int doStuff() { return 42; }
B int doStuff(int x) { return 42; }
C Foo doStuff(int x) { return new Foo(); }
D Object doStuff(int x) { return new Object(); }
E SuperFoo doStuff(int x) { return new Foo(); }

A, C, and E are correct. Options B and D are incorrect because an override cannot change the return type unless it's a valid covariant return. Option C is a valid covariant return.

No comments:

Post a Comment