2

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I'm gonna end up having to just implement a ByteBuffer in the class, rather than just extending it and inheriting its methods. Too much time and work to go digging around in there trying to figure out which classes do what.
0

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.

4 Comments

You've found something (similar to?) the factory pattern -- commonly used to provide a single "constructor" that knows how to make the correct type of an object based on its parameters.
@William, Its called using a Factory method and Polymorphism. Its a basic principle of Object Orientated design.
The best thing to read is the code, its pretty short for this method. ;)
There's so much abstraction in there, I can't tell which classes are just "describing" classes, and which ones are self-reliant and extendable. I don't think they needed to break it down so far.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.