从Java中的抽象类调用子类构造函数

Joe*_*oel 6 java

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()

Kev*_*son 8

我不确定是否可以在不进入循环的情况下执行此操作.我相信使用工厂方法而不是构造函数来编写它会更清楚.


Leo*_*kov 2

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)

看起来代码可能更简单。