微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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关键字!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。