为什么javaAPI中抽象的方法都能直接调用?
比如
private ByteBuffer bytebuffer;
...
...
jFormattedTextField2.setValue(new Double(this.bytebuffer.getInt(772)));
在这里,getInt()明明是抽象方法,为什么能直接调用呢?不是需要 重写 吗?(后面没有重写它)
比如
private ByteBuffer bytebuffer;
...
...
jFormattedTextField2.setValue(new Double(this.bytebuffer.getInt(772)));
在这里,getInt()明明是抽象方法,为什么能直接调用呢?不是需要 重写 吗?(后面没有重写它)
看bytebuffer肯定不是new ByteBuffer这么来的
要么是new它的子类,要么直接把子类的引用给他
类似于Object o = new String("hi, Object is just reference type, while String is the object type");
有抽象方法的类 一定是抽象类吧?或者接口?你能直接new一个抽象类或者接口么?显然不能嘛所以你用的时候一定是用他的子类或者实现类(看你的说法你应该是用到多态了嘛)这些类已经帮你写好了,方法也实现好了,不用你关心了
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会自动选择你的具体的实现类,也就是你使用的是哪个子类!