JayLo
JayLo

Reputation: 63

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;
   }

Upvotes: 1

Views: 60

Answers (2)

SamTebbs33
SamTebbs33

Reputation: 5647

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?

Upvotes: 1

Eran
Eran

Reputation: 393846

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.

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.

Upvotes: 1

Related Questions