@Alberth great answer.
@RidiculousName My personal opinion on the matter is that if you're going to compare the following:
x = 5;
or
public void setX(int x) { this.x = x; }
You have no real difference at face value but people will argue that this "protects" the variable from being changed. This really isn't true because you can still call the set method and fill x with any value. I'm a strong believer in doing what you need when it's required, and not simply following a "style" or "approach" because people tell you it 'should' be done like that. In my professional work I use JAVA only for android related stuff so it doesn't take up the majority of the programming I actually do. I have noticed that in JAVA it seems to be taught a lot more heavily as best practice to only used Set and Get methods when dealing with member variables. I guess it has to do with encapsulation. Do I personally use this approach? Yes and no... I will explain why.
If I only need to edit the variable without any additional steps then I wont bother. I have seen people flood their code with the following for every single member variable:
public void setX(int x) { this.x = x; }
public int getX() { return this.x; }
Now if I need to make a set for something like 'health', then I might do this because I can add in additional checks
public void setHP(int hp) {
if (hp > 0) {
this.hp = hp;
if (this.hp > this.maxHp) {
this.hp = this.maxHp;
}
}
}
Some advantages to having Set is that you can always go back in add additional validation if needed, but in my experience I design everything the best way from the start not requiring me to go back and add in additional checks.
Some people will use Get methods if they are wanting to retrieve something and that variable will never be edited either through a set method or directly and just helps prevent accidental editing.
What I personally do is use a setter if I need to add validation. I rarely use getters (unless I have to) as I don't recall anytime I ever accidentally modified a variable when asking to retrieve its value. If I'm working on a project quickly I find it faster to just work directly with the member variable unless I need validation.
At the end of the day it comes down to using what makes sense for the task at hand. Regardless, the beauty in programming is that you can achieve the same result in different ways.