Access modifiers restrict what can be accessed by code outside of objects. For instance, the private
keyword in many languages (C++, Java) sets members that can only be accessed by methods of the class. public
members can be accessed by any part of the program.
In general, a good programming practice is to make all data members within classes private
. This ensures we keep everything related to the data together (i.e., if we need to manipulate via methods). Data members should ideally be accessed or changed via getters or setters.
The access modifier works on the class level — two objects of the same class can access each other’s private members.1
Especially important if we rely on inheritance within our code, we can use the protected
keyword to denote class data that is accessible to derived classes but otherwise private.
Footnotes
-
From this answer on StackOverflow. ↩