来自 parents class 的链构造函数

Chain Constructor from parents class

对于class作业,我有几个class,

我在合成 class 和图片 class 方面遇到问题。

它说 Composite class 只有一个没有参数的构造函数,

但它需要图片中的链构造函数class。

这是我的合成class

public class Composite extends Picture {
    private ArrayList<Picture> components;

    public Composite (){
    //I have no idea how to chain.
    }
...

这是 Picture 的构造函数

public abstract  class Picture {
    private PicPoint base;

    public Picture(PicPoint base) {
        this.base = base;
    }
...

对于链接,我的赋值指令说

"A Composite is simply a collection of pictures which all take care of their own position. So, while Composite must have a base point, it really doesn’t mean anything"

"Composite will have a single constructor with no arguments. However, the constructor needs to chain with the constructor for Picture, which requires a point. Pass the PicPoint with coordinates NaN and NaN to the Picture constructor"

但我不知道如何链接构造函数。

P.S。这是测试 class.

方法的一部分
    PicPoint p0 = new PicPoint(0,0);
    PicPoint p1 = new PicPoint(3,0);
    PicPoint p2 = new PicPoint(0,4);
    Triangle t1 = new Triangle(p0,p1,p2);
    Circle c1 = new Circle(p1, 2);
    Rectangle r1 = new Rectangle(p2, 3, 4);
    Composite cmp1 = new Composite();
    cmp1.getComponents().add(t1);
    cmp1.getComponents().add(c1);
    cmp1.getComponents().add(r1);


    PicPoint p3 = new PicPoint(17, 23);
    PicPoint p4 = new PicPoint(-14,-5);
    PicPoint p5 = new PicPoint(3, -18);
    Triangle t2 = new Triangle(p3,p4,p5);
    Circle c2 = new Circle(p4, 2);
    Rectangle r2 = new Rectangle(p5, 3, 4);
    cmp2 = new Composite();
    cmp2.getComponents().add(t2);
    cmp2.getComponents().add(c2);
    cmp2.getComponents().add(r2);
    cmp2.getComponents().add(cmp1);


/*I tried 
public Composite(){
    super(new PicPoint(0, 0));
}
and that test class gave me tons of nullPointException*/

构造函数链背后的思想是,当子对象被实例化时,其构造函数调用其父构造函数。一个很好的理解方式是子构造函数只处理子构造函数独有的逻辑,而超级调用处理所有其他逻辑。

根据我对问题的理解,Composite 的构造函数应该如下所示:

public Composite() {
    super(new PicPoint(Double.NaN, Double.NaN)); //parent constructor call;
    // any other logic that is specific to the child class Composite
}