-2

Hello StackOverflow Community! I hope you're having a nice day.

I'm asking myself if I can just decrease an int obtained from a getXYZ() method of another class (the int should also be modified in the other class) or if I must use a setter?

for example:

Class: Monster

public int getHealth() {
    return health;
}

Class: Bullet

applyDamage(target);

private void applyDamage(Monster target) { 
    target.getHealth() - 1; // OR
    target.setHealth(4); 
}

3 Answers3

2

If you mean something like:

int value = object.getXYZ();
value--;

The code is valid but will not set the int in the other class. It will only decrease the value of the local variable you use to store the value.

 object.setXYZ(object.getXYZ() - 1);

Is what you're looking for.

This answer assumes that the int you want to set in the other class has the private modifier. If it is declared public you can just use object.XYZ--; for example.

ChristofferPass
  • 346
  • 1
  • 11
1

you can't change the original int value that you get from the getter because you get his value, not his place in the memory. to change the original value, you have to use setter(if the int is not static). in addition, it make the code more readable and organized

0

If you call a getXYZ() which return an int and then edit the int, the int in the class containing the int will not be changed.
Because you will have the value of that int not that int it self. You can say you will have your personal copy. Now whatever you do with you copy it will affect the main int.

You have to call the setter in that case.

private void applyDamage(Monster target) { 
    target.setHealth(target.getHealth() - 1); 
}
Saif
  • 6,804
  • 8
  • 40
  • 61