父母类的链构造函数

时间:2016-03-10 03:19:35

标签: java constructor constructor-chaining

对于课程作业,我有几个课程,

我有复合类和图片类的问题。

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

但它需要Picture类中的链构造函数。

这是我的复合课

public abstract  class Picture {
    private PicPoint base;

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

这是Picture的构造函数

    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将有一个没有参数的构造函数。但是,构造函数需要使用Picture的构造函数进行链接,这需要一个点。将带有坐标NaN和NaN的PicPoint传递给Picture构造函数”

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

P.S。这是测试类的方法的一部分。

System.out.println("\nPlease enter the letter you want to guess: ");
        char guessLetter = input.next().charAt(0);

        if (Character.isLetter(guessLetter)){
            System.out.println("Please enter the spaces you want to check (separated by spaces): ");
            String guessSpaces = input.next();


            for (int index = 0; guessSpaces.charAt(index) == ' ';index++){
                if(guessSpaces.charAt(index)== secretWord.indexOf(guessLetter)){
                    System.out.println("You guess is in the word");

1 个答案:

答案 0 :(得分:0)

构造函数链接背后的想法是,当实例化子对象时,其构造函数会调用其父构造函数。看到这个的一个好方法是子构造函数只处理子项唯一的逻辑,而超级调用处理所有其他逻辑。

根据我对问题的理解,Composite的构造函数看起来像这样:

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