简体   繁体   English

如何编写存取器和增幅器?

[英]how to write accessor and mutator?

calculate the amount of gas lost and set the car's current gas capacity to the new value. 计算损失的汽油量,并将汽车的当前汽油量设置为新值。 I forgot to add this part to the question. 我忘记将这部分添加到问题中。 the amount of gas does not exceed the top gas capacity. 气体量不超过最大气体容量。 I would like to know is this right? 我想知道是这样吗?

    private final int GAS_CAP = 30 

    public int getGasCapacity(int gasCapacity)
    {
      if(currentGas <= GAS_CAP)
      {
        gasCapacity = GAS_CAP - currentGas;
      }
     else gasCapacity = currentGas;
         return gasCapacity;
   }

Your method doesn't mutate the state of the object, it just returns a value. 您的方法不会改变对象的状态,它只会返回一个值。 You only assign a value to the gasCapacity parameter of the method, which is local to the method. 您只能为方法的gasCapacity参数分配一个值,该值是方法的局部值。

If it's supposed to mutate something, then you got this wrong. 如果应该突变某些东西,那么您就错了。

In addition, you are not doing anything with the value passed to your method in the gasCapacity variable, so your logic seems incorrect. 此外,您不会对gasCapacity变量中传递给您的方法的值做任何事情,因此您的逻辑似乎不正确。

You will probably need two methods for this, one to get the current gas (accessor) and one to set it (mutator). 为此,您可能需要两种方法,一种是获取当前气体(访问器),而另一种是设置它(更改器)。

public int getGasLost(){
    return GAS_CAP - currentGas;
}

public void setGasCapacity(int gasCapacity){
    GAS_CAP = gasCapacity;
}

However, since GAS_CAP seems to be a final value, you won't be able to change it, can you confirm this? 但是,由于GAS_CAP似乎是一个final值,您将无法更改它,您可以确认吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM