【问题标题】:Working with overloading but method does not return value. Any ideas? [closed]使用重载但方法不返回值。有任何想法吗? [关闭]
【发布时间】: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


【解决方案1】:

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

按照@Eran 的建议,尝试更改为:

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

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

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2017-06-23
    • 2021-12-26
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多