用Java将构造函数链接在一起

时间:2018-10-16 01:31:09

标签: java

我正在尝试创建一个程序,该程序将根据输入的尺寸量告诉您是否无能为力,直线,矩形或盒子。我们不允许使用this。“ variable”,而必须使用this。(“ parameters”)来链接构造函数。我面临的唯一问题是,除一个构造函数外,所有构造函数都在它们都链接到的一个构造函数中打印行。这是令人困惑的代码:

//Conner Cozine
public class OverloadedBox {

  //instance variables

  //default constructor
  public OverloadedBox(){
    this(0, 0, 0);
    System.out.println("Nothing is created");
  }
  //one parameter constructor
  public OverloadedBox(int l){
    this(l, 0, 0);
    System.out.println("A line is created");
  }
  //two parameter constructor
  public OverloadedBox(int l, int w){
    this(l, w, 0);
    System.out.println("A rectangle is created");
  }
  //three parameter constructor
  public OverloadedBox(int l, int w, int h){
    System.out.println("A box is made");

  }
}

测试类:

public class OverloadedBoxTest {
  public static void main(String[] args){
    //OverloadedBox b = new OverloadedBox(); //nothing
    //OverloadedBox b1 = new OverloadedBox(1, 3); //rectangle
    //OverloadedBox b2 = new OverloadedBox(1, 3, 4); //box
    //OverloadedBox b3 = new OverloadedBox(2); //line
  }

}

1 个答案:

答案 0 :(得分:1)

使用当前定义构造函数的方式,我认为您无法实现所需的功能。这是因为前三个全都叫第四个,所以总是打印第四个的输出。

您可以添加第五个私有构造函数以实现所需的目标:

public class OverloadedBox {
    //instance variables

    public OverloadedBox() {
        this(0, 0, 0, "nothing");
    }
    public OverloadedBox(int l) {
        this(l, 0, 0, "a line");
    }
    public OverloadedBox(int l, int w) {
        this(l, w, 0, "a rectangle");
    }
    public OverloadedBox(int l, int w, int h) {
        this(l, w, h, "a box");
    }
    private OverloadedBox(int l, int w, int h, String type) {
        System.out.println("Created " + type);
    }
}