首页 > 解决方案 > 使用重载但方法不返回值。有任何想法吗?

问题描述

所以我目前正在学习 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;
   }
}

标签: javaclassdebuggingmethods

解决方案


我认为您不需要在重载的构造函数中调用 getVolume() 方法。

正如@Eran 建议的那样,尝试更改为:

public DebugBox(int width, int length, int height)
{
   this.width = width;
   this.length = length;
   this.height = height;
}

您需要使用 this 的原因是因为您已将构造函数参数命名为与类字段属性相同,因此您需要使用“this”前缀引用外部属性。


推荐阅读