【发布时间】: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