【问题标题】:Static constructor in abstract class?抽象类中的静态构造函数?
【发布时间】:2013-03-12 05:40:22
【问题描述】:

考虑以下示例情况:

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()),因为 Parent 是抽象的,但我真的不想要 Parent。我希望这个方法自动提供给子类。

我更愿意对.allocate() 使用“静态构造函数”方法,而不是添加另一个可见的构造函数。

我有什么办法可以将此默认实现放在Parent 类中,还是每个子类都必须包含相同的代码?

我想另一种选择是从父级中去除“抽象”,但抽象适合——我从不想要父类型的对象。

提前致谢。

【问题讨论】:

  • 静态方法不被子类继承,所以这种方法从根本上是有缺陷的。也许你想要一个建造者?
  • 你打算如何使用它?你能举个例子吗?要调用Child.allocate,您需要在Child 中实现静态方法。
  • 另外,看看factory pattern
  • 不存在静态构造函数。
  • 结束时大声笑——很明显这是一个真正的问题——叹息

标签: java abstract-class static-constructor


【解决方案1】:

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

构建器/工厂模式是您尝试完成的更好的模式。您可以查看 JAX-RS Response 类或 DocumentBuilderFactory 类,了解如何实现这些模式的示例。

【讨论】:

  • 绝对是我认为静态方法会被继承的疏忽。尽管引用了 *Buffer allocate,但我什至没有考虑查看它的实现。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2023-03-04
  • 2015-03-20
  • 2011-03-21
  • 2011-07-21
相关资源
最近更新 更多