我正在尝试创建一个程序,它会告诉您是否可以根据您输入的尺寸量制作任何东西、一条线、一个矩形或一个盒子。我们不允许使用 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
}
}
最佳答案
按照当前定义构造函数的方式,我认为您无法实现您想要的。这是因为前三个都调用第四个,所以第四个的输出总是被打印。
您可以添加第五个私有(private)构造函数来实现您想要的:
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);
}
}
关于java - 在java中将构造函数链接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826748/