次のサンプル状況を検討してください。
public abstract class Parent
{
private ByteBuffer buffer;
/* Some default method implementations, interacting with buffer */
public static Parent allocate(int len)
{
// I want to provide a default implementation of this -- something like:
Parent p = new Parent();
p.buffer = ByteBuffer.allocate(len);
return p;
}
}
public class Child extends Parent
{
/* ... */
}
public class App
{
public static void main(String[] args)
{
// I want to ultimately do something like:
Child c = Child.allocate(10);
// Which would create a new child with its buffer initialized.
}
}
new Parent()
明らかに、親は抽象的であるため、これを行うことはできません ( ) が、実際には親は必要ありません。このメソッドをサブクラスに自動的に提供したい。
.allocate()
別の可視コンストラクターを追加する代わりに、「静的コンストラクター」アプローチを使用することをお勧めします。
このデフォルトの実装をParent
クラスに配置する方法はありますか?それとも、各サブクラスに同じコードを含める必要がありますか?
別のオプションは、親から「抽象」を取り除くことだと思いますが、抽象的に適合します-親タイプのオブジェクトは決して必要ありません。
前もって感謝します。