java - ByteBuffer类中的get方法为抽象的,为什么下面的程序可以直接使用?
黄舟
黄舟 2017-04-17 17:33:24
[Java讨论组]

import java.nio.*;
import java.nio.channels.*;
import java.io.*;

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());         // 抽象方法为什么可以直接使用?
  }
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
PHP中文网

public static ByteBuffer allocate(int capacity) {

    if (capacity < 0)
        throw new IllegalArgumentException();
    return new HeapByteBuffer(capacity, capacity);

}

allocate实例化返回的是个HeapByteBuffer。

class HeapByteBuffer extends ByteBuffer

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

怪我咯

查看源码可以知道

ByteBuffer buff = ByteBuffer.allocate(BSIZE);
这一步实例化了ByteBuffer的子类HeapByteBuffer

 public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }

而在HeapByteBuffer里面get(int i)方法被重写了

public byte get(int i) {
        return hb[ix(checkIndex(i))];
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号