This question already has an answer here:
- Why do we need private variables? 15 answers
Member variables of a class are typically hidden from the outside word (i.e., the other classes), with private access control modifier. Access to the member variables are provided via public assessor methods. This follows the principle of information hiding. That is, objects communicate with each others using well-defined interfaces (public methods). Objects are not allowed to know the implementation details of others. The implementation details are hidden or encapsulated within the class. Information hiding facilitates reuse of the class.
I have a question why set member variables as private and access these variables via public method is secure than direct access to member variables with public modifier. These 2 ways achieve the same result, meaning it both changes the values of member variables. Can anybody explain to me more clearly! Thanks,