Saturday, August 14, 2010

Covariant Returns:

Courtesy of


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

And four declarations:
I.   Foo doStuff(int x) { return new Foo(); }
II.  Foo doStuff(int x) { return new SuperFoo(); }
III. SuperFoo doStuff(int x) { return new Foo(); }
IV.  SuperFoo doStuff(int y) { return new SuperFoo(); }

Which, inserted independently at line 8, will compile?
a) Only I.
b) Only IV.
c) Only I and III.
d) Only I, II, and III.
e) Only I, III, and IV.
f) All four declarations will compile. 

e is correct. As of Java 5 when overriding methods, covariant return types (i.e. the subtype of the declared return type) are allowed. Note that II won't compile because SuperFoo is NOT a subtype of Foo, it is a superclass.

No comments:

Post a Comment