William the Coderer
William the Coderer

Reputation: 708

Java : Extending from ByteBuffer

Java will not allow me to extend from ByteBuffer because it implements abstract methods that I am not overriding, yet these methods work for any ByteBuffer objects that are created, such as asDoubleBuffer()...

byte[] bytes = new byte[256];
ByteBuffer buf = ByteBuffer.wrap(bytes);
DoubleBuffer db = buf.asDoubleBuffer();

Yet, if I extend a new class from ByteBuffer, it forces me to implement asDoubleBuffer(), even though the superclass already implements this method, obviously, since I can call it just fine. I'm totally not understanding what's going on here... Please explain this to me.

Upvotes: 2

Views: 1852

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

The ByteBuffer factory method returns a class which implements ByteBuffer.

byte[] bytes = new byte[256];
ByteBuffer buf = ByteBuffer.wrap(bytes);
System.out.println(buf.getClass());

prints

class java.nio.HeapByteBuffer

Using ByteBuffer is a relatively advanced tool, you need to understand Java pretty well before you try to extend it IMHO.


You can see this by looking at the code. In my IDE you can find it by doing a <shift>+<click> on the method.

public static ByteBuffer wrap(byte[] array) {
    return wrap(array, 0, array.length);
}

calls

public static ByteBuffer wrap(byte[] array,
                                int offset, int length)
{
    try {
        return new HeapByteBuffer(array, offset, length);
    } catch (IllegalArgumentException x) {
        throw new IndexOutOfBoundsException();
    }
}

BTW: I am a big fan of using ByteBuffer, however you really need to understand what you are doing to use it. esp when parsing data from a ByteBuffer. Developers with ten years experience find it tricky to use.

Upvotes: 4

William the Coderer
William the Coderer

Reputation: 708

Nevermind. I see that when a new ByteBuffer is allocated it returns a subclass that uses those abstract methods. The object created is not really a ByteBuffer at all. Confusing to me. Not sure why they would use this methodology.

Upvotes: 0

Related Questions