【发布时间】:2020-02-09 10:16:56
【问题描述】:
所以我目前正在学习 Java 课程,是的,我是 Java 新手。我知道其中一些代码看起来是多余的,但它就是这样。因此,本周我们正在使用名称相同但只接受某些数据类型的方法进行重载。这是我将用来调用其他 java 方法的主要方法。
// This class uses a DebugBox class to instantiate two Box objects
public class DebugFour3
{
public static void main(String args[])
{
int width = 12,
length = 10,
height = 8;
DebugBox box1 = new DebugBox();
DebugBox box2 = new DebugBox(width, length, height);
System.out.println("The dimensions of the first box are");
box1.showData();
System.out.print(" The volume of the first box is ");
showVolume(box1);
System.out.println("The dimensions of the second box are");
box2.showData();
System.out.print(" The volume of the second box is ");
showVolume(box2);
}
public static void showVolume(DebugBox aBox)
{
double vol = aBox.getVolume();
System.out.println(vol);
}
}
现在这里显示的第一组数据按原样工作,结果为 1。在将第二个框的信息传递给 Second DeBugBox 方法后,它不会将其传递给 get volume 并返回它.它只是返回 0 的长度宽度和高度和体积。
public class DebugBox
{
private int width;
private int length;
private int height;
public DebugBox()
{
length = 1;
width = 1;
height = 1;
}
public DebugBox(int width, int length, int height)
{
width = width;
length = length;
height = height;
getVolume();
}
public void showData()
{
System.out.println("Width: " + width + " Length: " +
length + " Height: "+ height);
}
public double getVolume()
{
double vol = length * width * height;
return vol;
}
}
【问题讨论】:
-
return vol;但您正在调用getVolume();并将其返回值分配给...究竟是什么? -
把
width = width改成this.width = width等等... -
另外,我不确定这个问题与重载有什么关系。
-
@FedericoklezCulloca OP 可能意味着重载的构造函数。
-
@FedericoklezCulloca 是的,它已分配给变量 vol。这就是返回的内容。
标签: java class debugging methods