Even a chimp can write code

Monday, December 06, 2004

Covariant return types, we like you but were doing okay without you

Until J2SE 1.4, it was illegal to have two methods in a class with similar signatures, but differing only in return types. Java 5 changes that so something like this is perfectly legal as long as the return type of the overriding method is a sub-class of the overridden method:


class Foo {}
class Bar extends Foo {}

public class Bat {

public Foo getObject() {
return new Foo();
}

}

public class Qux extends Bat {

// Bar is a sub-class of Foo, so this is legal
public Bar getObject() {
return new Bar();
}

}



So what does that tell us?

With covariant return types, the language spec concedes that creators of classes truly understand the polymorphic relationship of types. It thus takes the burden off the shoulders of API users making their life a tad easier (though not much).

Now, I have ranted before about useless language feature in Java 5 (here and here) and feel this falls right in that category. Surely, no one can claim this is absolutely required (simple workarounds exist). Besides, I have apprehensions about readability issues it introduces.

Email this | Bookmark this

2 Comments:

  • While I will agree that it is a 'nice-to-have', and not neccessarily a 'must-have', I don't think that invalidates covariance as useless. The same features can be said about inheritance.

    While workarounds exist in the pre-Java 5 days for this case, the advantage of covariance is found in the free documenting nature of the method. The client of a method is not required to explicitly cast the return value; the method itself can document that as an available value, thereby making the client code more straightforward and confident (as the cast is now part of the compiled API).

    The same negation you used on covariance can be used on auto-boxing and auto-un-boxing; and personally I feel there is a greater concern with those, as they potentially have a hidden impact on performance and memory.

    I suppose it is all about perspective...

    By Anonymous Anonymous, at December 6, 2004 at 2:06 PM  

  • I think it's about bloody time covariant return types were added to the language. They only simplify the programmer's job, get rid of a pointless complication in the type system and get rid of additional casts (and the potential static type errors that casts allow).

    Perhaps now we can have a public clone method?

    By Anonymous Anonymous, at December 7, 2004 at 6:02 AM  

Post a Comment | Home | Inference: my personal blog