Covariant overrides on the Buffer Hierachy

Richard Warburton richard.warburton at gmail.com
Tue Apr 15 08:05:50 UTC 2014


Hi,

I'd like to have a discussion about tidying up a few core library method
signatures in a way that (I think) is backwards compatible.

I've been using ByteBuffer quite a lot recently which is designed to be a
fluent API. Unfortunately its quite inconvenient to use because there's a
hierarchy of classes at play (MappedByteBuffer, ByteBuffer and Buffer) and
methods which are inherited from parent classes aren't overridden with
covariant return types. For example the following code doesn't compile
because clear is defined on Buffer and putInt is defined on ByteBuffer.

ByteBuffer buffer = ByteBuffer.allocate(256);

ByteBuffer other = buffer.duplicate()
                         .clear()
                         .putInt(0, 4);

If clear was overridden in ByteBuffer with ByteBuffer as its return type
then this would compile.

Now I can appreciate that these classes were introduced in Java 1.4, which
was before covariant overriding was possible, but I was wondering what the
situation was with fixing it. To my mind, and by all means correct me if
I've overlooked something, changing these methods to return their own type
rather than the parent type should be backwards compatible at the source
and binary levels.

The only issue that I'm aware of that is related to this kind of change is
the requirement to recompile all the classes in the hierarchy when making a
change [0]. If you don't do this its possible for an infinite recursion and
eventual stackoverflow to occur. Now as far as I can tell the
entire hierarchy of Buffer classes are all either package scoped classes,
or they are public classes with package scoped constructors. So I'm not
aware of a way to sub class them without the code being part of the JDK.
This would mean that the subclasses all need to be recompiled, satisfying
the safety criteria.

I'd be most appreciative of any feedback on this issue.

regards,

  Richard Warburton

  http://insightfullogic.com
  @RichardWarburto <http://twitter.com/richardwarburto>

[0]
http://mail.openjdk.java.net/pipermail/core-libs-dev/2012-January/009119.html
(thanks
to Stuart Marks for pointing this one out to me)


More information about the core-libs-dev mailing list