0

So I recently learned how to use classes and I am unsure about what is the best way to change a field in a class while in that class?

What I mean is I know that when I'm changing it in another class, I would do something like example.setX(0) to change the X value in that class since it is a private variable. But what is the better way to change the value using the code inside that class, should I just do x = 0, or setX(0), or this.setX(0)? What is the more recognized way of doing this?

PrimosK
  • 13,848
  • 10
  • 60
  • 78

5 Answers5

2

if you want to avoid the overhaead of calling the setter and you are sure there will 'never' be more in the setter than the assignment, it is ok to call

x = 0;
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
1
this.setX(0)

ensures additional logic required (if you set x, to you need to check y?) for changing variable is included. And this makes it clear the variable is in this.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
0

If you have a private global variable x in your class, you could just do

x = 0; //If you don't have another variable x defined for the method, if you do use

this.x = 0; 
0

You don't need to set it via setter, just write x = 0; you need getters and setters to reach variables from other classes.

leventcinel
  • 358
  • 2
  • 5
0

Typical way is to use normal assignment in Your class:

x = 5;

And use getters/ setters outside class.

object.setX(5);
Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63