java - 使用重载但方法不返回值。有任何想法吗?
问题描述
所以我目前正在学习 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;
}
}
解决方案
我认为您不需要在重载的构造函数中调用 getVolume() 方法。
正如@Eran 建议的那样,尝试更改为:
public DebugBox(int width, int length, int height)
{
this.width = width;
this.length = length;
this.height = height;
}
您需要使用 this 的原因是因为您已将构造函数参数命名为与类字段属性相同,因此您需要使用“this”前缀引用外部属性。
推荐阅读
- continuous-integration - Ci(TravisCI 和 CircleCI)中未安装 Cypress 版本
- plsql - PL/SQL Ttrigger 从具有相同行的 2 个表中选择数据
- jquery - 是否可以在分页点击时启动引导模式
- amazon-web-services - API Gateway + GovCloud + 带有 SSL 证书的自定义域名
- java - doFilter 和 HandlerInterceptorAdapter 可以在单个 spring 应用程序中一起使用吗
- windows - 检测 PE 文件中的无效资源部分
- matlab - 在matlab中生成特定的数字序列块
- javascript - Type .. 的参数不能分配给 Typescript 和单元测试中的 .. 类型的参数
- php - 将字符串转换为 JSON 并在 php 中另存为 .json 文件
- java - 将新元素插入表时执行任务