In code I've seen, some people often use private variables, e.g.
private static int number;
And they usually have access methods such as
public static int returnNumber(){
return number;
}
But my question is, what's the point? The way I do it is this
int number;
Followed by this when I need to access it
int numberToBeAssigned = someClass.number;
instead of
int numberToBeAssigned = someClass.getNumber();
To me it seems impractical to use accessor methods and private variables, I know what they do, the private variables are only allowed to be accessed by the class in which they are located. I just don't see the necessity for them, when you can just as easily instantialize the class and call upon its member variable when you need it. I'm obviously wrong in my logic, but I would like someone to give a clear example on how private variables along with accessor methods can be utilized.
Thank you
The point of accessors like this is to allow you to redesign the implementation without breaking all the rest of your code. For example, what if you decide later on that number
should come from a file? Or should be moved to another class?
If you've limited access to go through an accessor, then you can make changes like these and you only have to change the accessor -- you don't have to change all the other code that depends on it.