gpt4 book ai didi

使用多种方法的Java构造函数重载

转载 作者:搜寻专家 更新时间:2023-11-01 03:59:41 24 4
gpt4 key购买 nike

我在类里面有一个程序作业。我已经了解重载的基础知识,但我对某一点感到非常困惑。如何仅从我尝试使用的方法输出?好吧,让我向您展示代码而不是解释。

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 Box Object2,我想输出“用 XX 的长度和 XX 的宽度创建的矩形”。我不确定接下来要添加什么才能发生这种情况。任何帮助将不胜感激。

最佳答案

我猜

  Box BoxObject1 = new Box(1,0,0);
Box BoxObject2 = new Box(1,2,0);
Box BoxObject3 = new Box(1,2,3);

本来就是

  Box BoxObject1 = new Box(1);
Box BoxObject2 = new Box(1,2);
Box BoxObject3 = new Box(1,2,3);

目前,您的所有三个调用都在调用第三个构造函数(为某些参数传递 0)。

关于使用多种方法的Java构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com