使用多种方法重载Java构造函数
我在课堂上有一个项目作业。我已经理解了超载的基本原理,但有一点我完全搞不清楚。如何仅从我尝试使用的方法中输出?好吧,让我给你看看代码,而不是解释
public class Box {
private int length, width, height;
public Box(int length){
this.length=length;
System.out.println("Line created with length of" + length + ".");
}
public Box(int length, int width){
this.length = length;
this.width = width;
System.out.println("Rectangle created with the length of " + length + " ");
System.out.println("and the width of " + width + ".");
}
public Box(int length, int width, int height){
this.length=length;
this.width=width;
this.height=height;
System.out.println("Box created with the length of " + length + ", ");
System.out.println("the width of " + width + ", ");
System.out.println("and the height of " + height +".");
}
}
class BoxTest {
public static void main(String[] args) {
Box BoxObject1 = new Box(1,0,0);
Box BoxObject2 = new Box(1,2,0);
Box BoxObject3 = new Box(1,2,3);
}
}
那好吧!如何调用类BoxTest只输出给定的内容。例如,使用Box-BoxObject1,我想输出“长度为XX的线条”,而不是其他线条。对于Box Object2,我想输出“长度为XX,宽度为XX的矩形”。我不知道接下来该怎么做才能让这一切发生。任何帮助都将不胜感激
共 (0) 个答案