public abstract class Parent {
private Parent peer;
public Parent() {
peer = new ??????("to call overloaded constructor");
}
public Parent(String someString) {
}
}
public class Child1 extends parent {
}
public class Child2 extends parent {
}当我构造一个对等实例时,我希望自动构造一个同样属于Child1类型的“Child1”,并将其存储在peer属性中。对于类型为Child2的对等体,Child2也是如此。
问题是,在父类中的peer属性的分配上。我不能通过调用new Child1()来构造一个新的子类,因为那样对Child2就不起作用了。我该怎么做呢?有没有一个关键字可以用来指代这个子类?像new self()这样的东西
发布于 2009-05-21 09:39:32
public abstract class Parent implements Clonable{
private Object peer;
// Example 1
public Parent() {
try {
peer = this.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
// Example 2
public Parent(String name) {
try {
peer = this.getClass().getConstructor(String.class).newInstance(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public <T extends Parent> T getPeer() {
return (T)peer;
}
}
public class Child01 extends Parent { }
public class Child02 extends Parent { }看起来代码可能更简单。
发布于 2009-05-21 08:09:47
我不确定是否有可能在不陷入循环的情况下做到这一点。我确信,使用工厂方法而不是构造函数来编写它会更清晰。
发布于 2009-05-21 10:11:36
我首先要说的是,我认为这可能是一个非常糟糕的设计。类名也很糟糕,但我将继续使用它们。
然而,处理它的一种方法是:
public abstract class Parent {
interface PeerFactory {
Parent create(Parent peer);
}
private final Parent peer;
protected Parent(Parent peer) {
super();
this.peer = peer;
}
protected Parent(PeerFactory peerFactory) {
super();
this.peer = peerFactory.create(this);
}
}
public class Child1 extends parent {
private static final PeerFactory peerFactory = new PeerFactory {
public Parent create(Parent peer) {
return new Child1(peer);
}
};
public Child1() {
super(peerFactory);
}
private Child1(Peer peer) {
super(peer);
}
}https://stackoverflow.com/questions/891824
复制相似问题