PRIVATE FIELDS AND METHODS
True object-oriented languages can protect fields of objects from direct manipulation by other objects' methods. A private field is one that cannot be fetched or updated from any function or method declared outside the object; a private method is one that cannot be called from outside the object. Privacy is enforced by the type-checking phase of the compiler. In the symbol table of C, along with each field offset and method offset, is a boolean flag indicating whether the field is private. When compiling the expression c.f() or c.x, it is a simple matter to check that field and reject accesses to private fields from any method outside the object declaration. There are many varieties of privacy and protection. Different languages allow
- Fields and methods which are accessible only to the class that declares them.
- Fields and methods accessible to the declaring class, and to any subclasses of that class.
- Fields and methods accessible only within the same module (package, namespace) as the declaring class.
- Fields that are read-only from outside the declaring class, but writable by methods of the class.
In general, these varieties of protection can be statically enforced by compiletime type-checking, for class-based languages.