abstract methods in ByteBuffer class
I'am a little confused with abstract methodsget() andput() inByteBuffer class.
Java API says:
publicabstractclass ByteBuffer
extends Bufferimplements Comparable
{
// This is a partial API listing
publicabstractbyte get( );
publicabstractbyte get (int index);
publicabstract ByteBuffer put (byte b);
publicabstract ByteBuffer put (int index,byte b);
}
Question is:
How can I call methodsget() and/orput() when they are abstract - not implemented in ByteBuffer class?
Thanks
You can't. But you can call those methods on non-abstract subclasses of ByteBuffer. And there's probably a method you can call to get a ByteBuffer object. That method will return an instance of a subclass of ByteBuffer. Such an object is a ByteBuffer object, even if it's also another kind of object.
When you call that method, do:
System.out.println(theObject.getClass().getName());
and see what you get.
Like this:
import java.nio.*;
public class BufferExample {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.wrap(new byte[]{10, 11, 12});
while (b.hasRemaining()) {
System.out.println(b.get());
}
}
}
thanks paulcw !
System.out.println(theObject.getClass().getName());
gives me : java.nio.HeapByteBuffer
I was not find HeapByteBuffer while navigating javadoc for API - and I still cant find it. I have installed JDK 1.5.0.9.
Why in the java API for ByteBuffer, there is no information that HeapByteBuffer is subclass of ByteBuffer ?
Why is it hidden from us?
Yeah, it's a subclass of ByteBuffer. You can find out more about the class by using introspection.
But, you don't have to, to use this API. This is called "design-by-contract" (well, part of it anyway), and that's why the class is hidden with respect to the API docs. The idea is that an API is kind of like a contract, an agreement between the designer and the user of the API. The user of the API is given just what s/he needs to do the job. The designer might implement the API with more stuff that is immediately apparent, but the user doesn't need to know that stuff to use the API. This provides a good layer of abstraction around the API and makes code more flexible.
So, it's good to know how these things work -- that the ByteBuffer contract is serviced by hidden implementing classes -- but you don't have to know that to use ByteBuffer, and in fact you'd probably only make things difficult (buggy and hard to maintain) if you wrote code that used the fact that apparently the implementing subclass of ByteBuffer is HeapByteBuffer.