抽象类中的静态构造函数?

jed*_*rds 3 java abstract-class static-constructor

请考虑以下示例情况:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

很显然,我不能这样做(new Parent()),因为家长是抽象的,但我并不真的想要一个家长.我希望将此方法自动提供给子类.

我宁愿使用"静态构造函数"方法.allocate()而不是添加另一个可见的构造函数.

我是否有办法将此默认实现放在Parent类中,或者每个子类是否必须包含相同的代码?

我想另一个选择是从父级中删除"抽象",但抽象适合 - 我从不想要类型为Parent的对象.

提前致谢.

Per*_*ion 5

如果检查标准JDK中的Buffer类集合,您会注意到每个特化(ByteBuffer,CharBuffer,DoubleBuffer等)都有自己allocate定义的静态方法.有一个原因他们并不是都从一个公共基类继承 - 静态方法不会被继承!相反,它们与定义它们的类相关联,并且只能访问类级变量.

您要完成的更好的模式是构建器/工厂模式.您可以检查JAX-RS Response类或DocumentBuilderFactory类,以获取有关如何实现这些模式的示例.