0
abstract class IntBuffer

とにかく、このクラスのインスタンスを作成できないようです。abstract が宣言されているためですが、同時に、静的ファクトリ メソッドが IntBuffer allocate(int capacity)あり、単純にインスタンスを作成できますBuffer b=IntBuffer.allocate(128) が、待機してください。IntBuffer は抽象的であり、持っていません。定義済みの具象サブクラス。これはどのように機能しますか?

編集 - - - - - - -

IntBuffer のサブクラスを返すのではないかと疑っていましたが、HeapIntBuffer やそのようなサブクラスが見つかりませんでした。内密に宣言してるのかしら?? したがって、 api doc にはありません!

4

2 に答える 2

2

静的メソッドがあるからといって、ただ のインスタンスを作成しているわけではありませんIntBuffer。以下は、ファクトリ メソッドで実行できることの短い例です。

abstract class Abstract {
   static Abstract createInstance(int size) {
       return size < 10 ? new SmallImplementation() : new LargeImplementation();
   }

   public abstract String getDescription();
}

class SmallImplementation extends Abstract {
   @Override public String getDescription() {
       return "I'm an implementation for small sizes";
   }
}

class LargeImplementation extends Abstract {
   @Override public String getDescription() {
       return "I'm an implementation for large sizes";
   }
}

public class Test {
   public static void main(String[] args) throws InterruptedException {
       Abstract small = Abstract.createInstance(1);
       Abstract large = Abstract.createInstance(100);
       System.out.println(small.getDescription());
       System.out.println(large.getDescription());
   }
}

これは基本的にポリモーフィズムの核心Test.main ですAbstract。適切な実装を選択するのは、ファクトリ メソッド次第です。

于 2015-03-02T14:00:58.027 に答える
1

allocate は IntBuffer を返すのではなく、IntBuffer のサブクラスを返すため、機能します。IntBuffer.allocate のソース コードは次のとおりです。

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

クラス HeapIntBuffer は IntBuffer を拡張するため、コードで次のように記述します。

IntBuffer myBuffer = IntBuffer.allocate(size);

割り当ては問題ありません。

于 2015-03-02T14:02:04.987 に答える