开发者社区> 问答> 正文

ByteBuffer类中的get方法为抽象的为什么可以直接使用?

ByteBuffer类中的get方法为抽象的,为什么下面的程序可以直接使用?
screenshot

public class GetChannel {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    // Write a file:
    FileChannel fc =
      new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();
    // Add to the end of the file:
    fc =
      new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size()); // Move to the end
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();
    // Read the file:
    fc = new FileInputStream("data.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while(buff.hasRemaining())
      System.out.print((char)buff.get());         // 抽象方法为什么可以直接使用?
  }
}

展开
收起
蛮大人123 2016-03-11 19:07:50 2651 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    public static ByteBuffer allocate(int capacity) {
    
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }
    allocate实例化返回的是个HeapByteBuffer。
    class HeapByteBuffer extends ByteBuffer

    所以此处是父类的抽象方法调用具体的子类实例化的方法

    2019-07-17 18:59:56
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
继承与功能组合 立即下载
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载