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 {
}
Run Code Online (Sandbox Code Playgroud)
当我构造一个Child1的实例时,我想要一个自动构造的"peer",它也是Child1类型,并存储在peer属性中.同样对于Child2,具有Child2类型的对等体.
问题是,在父类中分配对等属性.我无法通过调用构造一个新的Child类,new Child1()因为它对Child2不起作用.我怎样才能做到这一点?我可以使用哪个关键字来引用子类?有点像new self()?
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 { }
Run Code Online (Sandbox Code Playgroud)
看起来代码可能更简单。
| 归档时间: |
|
| 查看次数: |
9604 次 |
| 最近记录: |