Typically, it is good practice for your class variables to be private, which means they can't be set except by methods and constructors of the class the variables belong to. The advantage of using methods to set variables (these methods are referred to as setters
) is that you can provide validation logic within the method.
For example, if you have a variable within your class that is supposed to represent the hour of the day, you will only want it to hold a value 0 to 23. Your setter can throw an exception any time the user of the method attempts to set the variable to anything outside this range.