Field encapsulation


In computer programming, field encapsulation involves providing methods that can be used to read from or write to the field rather than accessing the field directly. Sometimes these accessor methods are called getX and setX, which are also known as mutator methods. Usually the accessor methods have public visibility while the field being encapsulated is given private visibility - this allows a programmer to restrict what actions another user of the code can perform. Compare the following Java class in which the name field has not been encapsulated:

public class NormalFieldClass

with the same example using encapsulation:

public class EncapsulatedFieldClass

In the first example a user is free to use the public name variable however they see fit - in the second however the writer of the class retains control over how the private name variable is read and written by only permitting access to the field via its getName and setName methods.

Advantages

Access to a subroutine involves additional overhead not present when data is accessed directly. While this is becoming of less concern with the wide availability of fast general-purpose processors it may remain important in coding some real-time computing systems and systems using relatively slow and simple embedded processors. In some languages, like C++, the getter / setter methods are usually inline functions, so that when inlining is performed, the code looks just like direct field accessing.