为什么javaAPI中抽象的方法都能直接调用?
比如
private ByteBuffer bytebuffer;
...
...
jFormattedTextField2.setValue(new Double(this.bytebuffer.getInt(772)));
在这里,getInt()明明是抽象方法,为什么能直接调用呢?不是需要 重写 吗?(后面没有重写它)

解决方案 »

  1.   

    bytebuffer的实际类型是ByteBuffer 的子类型
      

  2.   

    ByteBuffer是bytebuffer的reference type,不是真正的object type
    看bytebuffer肯定不是new ByteBuffer这么来的
    要么是new它的子类,要么直接把子类的引用给他
    类似于Object o = new String("hi, Object is just reference type, while String is the object type");
      

  3.   

    我是说,为什么能用getInt()方法,(我知道bytebuffer对象能用),在java API中,abstract int getInt(),而abstract方法不是应该自己重写的吗?
      

  4.   

    编译器不知道你的这个到底是bytebuffer,还是他的具体实现的某个子类。bytebuffer=new ByteBufferSon()。当你调用getInt()的时候,bytebuffer应该已经是某个具体子类的实例了,不然就nullpointexception了。
      

  5.   


    有抽象方法的类 一定是抽象类吧?或者接口?你能直接new一个抽象类或者接口么?显然不能嘛所以你用的时候一定是用他的子类或者实现类(看你的说法你应该是用到多态了嘛)这些类已经帮你写好了,方法也实现好了,不用你关心了
      

  6.   


    class abstract ByteBuffer {
       public abstract int getInt(int i);
       ...
    }class ByteBufferSubclass1 extends ByteBuffer {
       public int getInt(int i){
         System.out.println(" use ByteBufferSubclass1 ");
       }
    }class ByteBufferSubclass2 extends ByteBuffer {
       public int getInt(int i){
         System.out.println(" use ByteBufferSubclass2 ");
       }
    }class Test {
      private ByteBuffer bytebuffer;   public Test (ByteBuffer subClass){
          bytebuffer = subClass;
      }  public ByteBuffer getByteBuffer(){
          return bytebuffer;
      }  public static void main(String[] args) {
          Test test1 = new Test(new ByteBufferSubclass1());
          test1.getByteBuffer().getInt(1);      Test test2 = new Test(new ByteBufferSubclass2());
          test1.getByteBuffer().getInt(1);
      }
    }
    输出  
    use ByteBufferSubclass1 
    use ByteBufferSubclass2 jvm会自动选择你的具体的实现类,也就是你使用的是哪个子类!