Java为什么要将第二个实例的参数分配给一个类的两个实例?

问题描述

我正在上入门级的大学程序设计课,这也许是一个新手问题,但是我无法在其他地方找到答案,也无法弄清楚为什么Java从我的第二个Conveyor实例中分配了参数到两个实例。

这是我的传送带课程:

    public class Conveyor
    {
       //fields
       private static String type;
       private static double speed; //Speed is measured in m/s (meters/second)
       
       //constructors
       public Conveyor(String type,double speed)
       {
          this.type = type;
          this.speed = 0;
          this.speed = setSpeed(speed);
       }
       
       //methods
       public String getType()
       {
          return this.type;
       }
       
       public double getSpeed()
       {
          return this.speed;
       }
       
       public double setSpeed(double speed)
       {  
          if(speed <= 0)
          {
             this.speed = this.speed;
          }
          else
          {
             this.speed = speed;
          }
          
          return this.speed;
       }
       
       public double timeToTransport(double distance)
       {
          double t = distance / getSpeed();
          return t;
       }
    }

以及用于测试的Conveyor App:

    public class ConveyorApp
    {
       public static void main(String[] args)
       {
          Conveyor c1 = new Conveyor("flat belt",0.9);
          Conveyor c2 = new Conveyor("roller",-0.5);
          
          System.out.printf("Conveyor 1: %s conveyor with a speed of %.1f\n",c1.getType(),c1.getSpeed());
          System.out.printf("Time to transport an item 50m: %.1f\n\n",c1.timeToTransport(50));
          
          System.out.printf("Conveyor 2: %s conveyor with a speed of %.1f\n",c2.getType(),c2.getSpeed());
          System.out.printf("Time to transport an item 50m: %.1f\n\n",c2.timeToTransport(50));
       }
    }

如果我将第二个实例移到第一个实例的打印语句下方,则会产生预期的行为并打印:

    Conveyor 1: flat belt conveyor with a speed of 0.9
    Time to transport an item 50m: 55.6
    
    Conveyor 2: roller conveyor with a speed of 0.0
    Time to transport an item 50m: Infinity

否则,按照上面显示的顺序,这是我的输出:

    Conveyor 1: roller conveyor with a speed of 0.0
    Time to transport an item 50m: Infinity
    
    Conveyor 2: roller conveyor with a speed of 0.0
    Time to transport an item 50m: Infinity

我在做什么错了?

解决方法

“传送带”类的字段被标记为静态字段,但听起来您希望它们表现为实例字段。

  public class Conveyor
    {
       //fields
       private String type;
       private double speed; //Speed is measured in m/s (meters/second)
       ...
       

您只需要做的就是删除static关键字!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...