+ 1
How does the getter and setter will protect the data? I don't understand.
1 ответ
+ 4
When variables are made private, they cannot be accessed outside the class. If they need to be accessed however, using getter and setter methods instead of just making the variable public is more secure because they allow you to control how the data is accessed.
With public variables, you can change them to any value allowed by the data or object type. Sometimes any value is not a good idea for what the functionality of a class.
With a setter method, you can implement extra checks to make sure that the value the programmer or user wants to set is one that is suitable for the program.
The getter method would allow you to retrieve the value of the private variable and carry out extra tasks if required the setter would enable you more to have more control over what data is assigned to the variable as well as add other functionality if needed.