#why getters and setters
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Not quite - by doing so we have more control over what type of access occurs. We can add logic into the getters and setters (or not have then at all) that controls what happens when. Imagine a setter where there is a condition like:
public void setVariable(int variable) {
if (variable > 10) {
System.out.println("Too big!");
return;
}
this.variable = variable;
}
A very simple example but now we can control what occurs to the variable when. If the value was accessed just as the variable itself:
myObject.variable = 11;
We have lost all control over how access to the object proceeds
We can also control things in the getter such as "Is this user authenticated?" (This probably won't happen in a getter itself and some other class would be called first but the idea remains the same)
We also might only want people to read a value versus setting it: so only a getter. Again, with a public/global variable we lose that control.
Plus you prevent yourself from overwriting values